Home Database Mysql Tutorial mongodb 文档的嵌入和引用

mongodb 文档的嵌入和引用

Jun 07, 2016 pm 04:35 PM
mongodb relation Embed Quote document

mongodb 是介于关系型与非关系型数据之间的,mongodb的join查询可以通过引用来实现。可以将文档内容嵌入到另一个文档中,也可以将文档内容引用到另一个文档中。嵌入意味着要把某一类型的数据,如包含更多数据的数组,嵌入到文档本身。引用意味着创建一个引用

mongodb 是介于关系型与非关系型数据之间的,mongodb的join查询可以通过引用来实现。 可以将文档内容嵌入到另一个文档中,也可以将文档内容引用到另一个文档中。 嵌入意味着要把某一类型的数据,如包含更多数据的数组,嵌入到文档本身。 引用意味着创建一个引用,包含另一个文档的数据。相当于关系型数据库。 一. 嵌入 例如:我想使用一个关系型数据库来记录CD、DVD和购买信息。在这个数据中,需要一个表来收集CD,另一个表来存储CD歌曲信息。因此,如果要查询特定的信息就可能需要查询多个表的。 对于mongodb 或者其他非关系型数据库,会更容易的嵌入这些信息,采用这种方法会使数据库简洁,确保所有相关信息保存在单一的文档中,同时,检索数据更快。 数据结构如下: 关系型
|_media
	|_cds
		|_id, artist, title, genre, releasedate
	|_ cd_tracklists
		|_cd_id, songtitle, length
Copy after login
非关系型
|_media
	|_items
		|_
Copy after login
对于非关系型,文档看起来如下所示
[
        {
                "_id" : ObjectId("5353463193efef02c962da73"),
                "Type" : "CD",
                "Artist" : "Nirvana",
                "Title" : "Nevermind",
                "Tracklist" : [
                        {
                                "Track" : "1",
                                "Title" : "Smells like teen spirit",
                                "Length" : "5:02"
                        },
                        {
                                "Track" : "2",
                                "Title" : "In Bloom",
                                "Length" : "4:15"
                        }
                ]
        }
]
Copy after login
上面这个例子中,歌曲信息嵌入到文档本身中,在关系型数据库中至少需要两个表,在非关系型数据库中,仅需要一个集合和一个文档。在检索信息时,只需要数据从一个文档加载到内存中,而不必加载多个文档。 二. 引用 在很多场景下,把数据嵌入到文档足以满足很多应用程序,如上所示。然而,有时就需要引用另一个文档。 在mongodb中的文档引用是通过执行额外的查询来解决的。 mongodb提供两种方式来实现:手动引用和使用DBRef标准。 2.1 手动引用 手动引用是最简单最直接的方式。当手动引用数据时,将其他文档的_id值存储在你的文档中。实例如下:
> use ttlsa_com
switched to db ttlsa_com
> apress = ( { "_id" : "Apress", "Type" : "Technical Publisher", "Category" : ["IT", "Software","Programming"] } )
{
        "_id" : "Apress",
        "Type" : "Technical Publisher",
        "Category" : [
                "IT",
                "Software",
                "Programming"
        ]
}
> db.publisherscollection.insert(apress)
Copy after login
引用
> book = ( { "Type" : "Book", "Title" : "Definitive Guide to MongoDB, the", "ISBN" : "987-1-4302-3051-9", "Publisher" : "Apress","Author" : ["Membrey,Peter","Plugge, Eelco","Hawkins, Tim"] } )
{
        "Type" : "Book",
        "Title" : "Definitive Guide to MongoDB, the",
        "ISBN" : "987-1-4302-3051-9",
        "Publisher" : "Apress",
        "Author" : [
                "Membrey,Peter",
                "Plugge, Eelco",
                "Hawkins, Tim"
        ]
}
> db.mediaCollection.insert(book)
Copy after login
检索
> book = db.mediaCollection.findOne({"ISBN" : "987-1-4302-3051-9"})
{
        "Author" : [
                "Hawkins, Tim",
                "Plugge, Eelco"
        ],
        "ISBN" : "987-1-4302-3051-9",
        "Publisher" : "Apress",
        "Title" : " Different Title 2",
        "Type" : "Book",
        "_id" : ObjectId("5353462f93efef02c962da71")
}
> book.Publisher
Apress
> db.publisherscollection.findOne( { _id : book.Publisher } )
{
        "_id" : "Apress",
        "Type" : "Technical Publisher",
        "Category" : [
                "IT",
                "Software",
                "Programming"
        ]
}
Copy after login
2.2?DBRef DBRef提供了一个更正式的规范引用文档之间的数据。 在DBRef中,数据库引用以标准的JSON/ BSON嵌入对象存储的。 语法:?{ $ref : , $id : [, $db : ] } 代表引用的集合的名称。 所引用的文档的_id值。 $ db是可选的,引用的文档所在的数据库的名称。  
> apress = ( { "Type" : "Technical Publisher", "Category" :["IT","Software","Programming"] } )
{
        "Type" : "Technical Publisher",
        "Category" : [
                "IT",
                "Software",
                "Programming"
        ]
}
> db.publisherscollection.save(apress)
> apress
{
        "Type" : "Technical Publisher",
        "Category" : [
                "IT",
                "Software",
                "Programming"
        ],
        "_id" : ObjectId("53588c221697e7511678752c")
}
> book = { "Type" : "Book", "Title" : "Definitive Guide to MongoDB, the", "ISBN" : "987-1-4302-3051-9", "Author": ["Membrey, Peter","Plugge,Eelco","Hawkins, Tim"], Publisher : [ new DBRef ('publisherscollection',apress._id) ] }
{
        "Type" : "Book",
        "Title" : "Definitive Guide to MongoDB, the",
        "ISBN" : "987-1-4302-3051-9",
        "Author" : [
                "Membrey, Peter",
                "Plugge,Eelco",
                "Hawkins, Tim"
        ],
        "Publisher" : [
                DBRef("publisherscollection", ObjectId("53588c221697e7511678752c"))
        ]
}
> db.media.save(book)
> db.media.find().toArray()
[
        {
                "_id" : ObjectId("53588ce01697e7511678752d"),
                "Type" : "Book",
                "Title" : "Definitive Guide to MongoDB, the",
                "ISBN" : "987-1-4302-3051-9",
                "Author" : [
                        "Membrey, Peter",
                        "Plugge,Eelco",
                        "Hawkins, Tim"
                ],
                "Publisher" : [
                        DBRef("publisherscollection", ObjectId("53588c221697e7511678752c"))
                ]
        }
]
Copy after login
三. 比较 嵌入 : 小的子文档 数据不经常改变 当最终一致性是可以接受的 文档增长小 经常需要进行二次查询来获取数据 读快 引用 : 大的子文档 非易失性数据 当实时一致性是必要的 文档增长大 经常需要从结果中排除数据 写快
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

golang framework document usage instructions golang framework document usage instructions Jun 05, 2024 pm 06:04 PM

How to use Go framework documentation? Determine the document type: official website, GitHub repository, third-party resource. Understand the documentation structure: getting started, in-depth tutorials, reference manuals. Locate the information as needed: Use the organizational structure or the search function. Understand terms and concepts: Read carefully and understand new terms and concepts. Practical case: Use Beego to create a simple web server. Other Go framework documentation: Gin, Echo, Buffalo, Fiber.

How to configure MongoDB automatic expansion on Debian How to configure MongoDB automatic expansion on Debian Apr 02, 2025 am 07:36 AM

This article introduces how to configure MongoDB on Debian system to achieve automatic expansion. The main steps include setting up the MongoDB replica set and disk space monitoring. 1. MongoDB installation First, make sure that MongoDB is installed on the Debian system. Install using the following command: sudoaptupdatesudoaptinstall-ymongodb-org 2. Configuring MongoDB replica set MongoDB replica set ensures high availability and data redundancy, which is the basis for achieving automatic capacity expansion. Start MongoDB service: sudosystemctlstartmongodsudosys

Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Apr 18, 2025 am 11:48 AM

When developing an e-commerce website, I encountered a difficult problem: how to provide users with personalized product recommendations. Initially, I tried some simple recommendation algorithms, but the results were not ideal, and user satisfaction was also affected. In order to improve the accuracy and efficiency of the recommendation system, I decided to adopt a more professional solution. Finally, I installed andres-montanez/recommendations-bundle through Composer, which not only solved my problem, but also greatly improved the performance of the recommendation system. You can learn composer through the following address:

How to ensure high availability of MongoDB on Debian How to ensure high availability of MongoDB on Debian Apr 02, 2025 am 07:21 AM

This article describes how to build a highly available MongoDB database on a Debian system. We will explore multiple ways to ensure data security and services continue to operate. Key strategy: ReplicaSet: ReplicaSet: Use replicasets to achieve data redundancy and automatic failover. When a master node fails, the replica set will automatically elect a new master node to ensure the continuous availability of the service. Data backup and recovery: Regularly use the mongodump command to backup the database and formulate effective recovery strategies to deal with the risk of data loss. Monitoring and Alarms: Deploy monitoring tools (such as Prometheus, Grafana) to monitor the running status of MongoDB in real time, and

Navicat's method to view MongoDB database password Navicat's method to view MongoDB database password Apr 08, 2025 pm 09:39 PM

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

How to find Java framework documentation and tutorials for advanced developers? How to find Java framework documentation and tutorials for advanced developers? Jun 05, 2024 am 09:02 AM

For advanced Java developers, the official documentation (SpringBoot, Hibernate, etc.) provides comprehensive information, including API reference and best practices. Technical tutorial platforms (DZone, Baeldung, etc.) cover advanced features, design patterns, and code extensibility. Open source projects (GitHub, Maven, etc.) showcase real-world implementations to learn best practices and seek community support.

What is the CentOS MongoDB backup strategy? What is the CentOS MongoDB backup strategy? Apr 14, 2025 pm 04:51 PM

Detailed explanation of MongoDB efficient backup strategy under CentOS system This article will introduce in detail the various strategies for implementing MongoDB backup on CentOS system to ensure data security and business continuity. We will cover manual backups, timed backups, automated script backups, and backup methods in Docker container environments, and provide best practices for backup file management. Manual backup: Use the mongodump command to perform manual full backup, for example: mongodump-hlocalhost:27017-u username-p password-d database name-o/backup directory This command will export the data and metadata of the specified database to the specified backup directory.

How to choose a database for GitLab on CentOS How to choose a database for GitLab on CentOS Apr 14, 2025 pm 04:48 PM

GitLab Database Deployment Guide on CentOS System Selecting the right database is a key step in successfully deploying GitLab. GitLab is compatible with a variety of databases, including MySQL, PostgreSQL, and MongoDB. This article will explain in detail how to select and configure these databases. Database selection recommendation MySQL: a widely used relational database management system (RDBMS), with stable performance and suitable for most GitLab deployment scenarios. PostgreSQL: Powerful open source RDBMS, supports complex queries and advanced features, suitable for handling large data sets. MongoDB: Popular NoSQL database, good at handling sea

See all articles