Hướng dẫn mongodb self referencing collection
Docs Home → MongoDB Manual Show For many use cases in MongoDB, the denormalized data model where related data is stored within a single document is optimal. However, in some cases, it makes sense to store related information in separate documents, typically in different collections or databases. ImportantYou can use the You can also use the
This page outlines alternative procedures that predate the MongoDB applications use one of two methods to relate documents:
To resolve DBRefs, your application must perform additional queries to return the referenced documents. Some MongoDB drivers provide helper methods to enable DBRefs to be resolved into documents, but it doesn't happen automatically. DBRefs provide a common format and type to represent relationships among documents. The DBRef format also provides common semantics for representing links between documents if your database must interact with multiple frameworks and tools. Unless you have a compelling reason to use DBRefs, use manual references instead. A manual reference is the practice of including one document's Consider the following operation to insert two documents, using the
Then, when a query returns the document from the For nearly every case where you want to store a relationship between two documents, use manual references. The references are simple to create and your application can resolve references as needed. The only limitation of manual linking is that these references do not convey the database and collection names. If you have documents in a single collection that relate to documents in more than one collection, you may need to consider using DBRefs. DBRefs are a convention for representing a document, rather than a specific reference type. They include the name of the collection, and in some cases the database name, in addition to the value from the Optionally, DBRefs can include any number of other fields. Extra field names must follow any rules for field names imposed by the server version. DBRefs have the following fields: $ref The $id The $db Optional. Contains the name of the database where the referenced document resides. ExampleDBRef documents resemble the following document:
Consider a document from a collection that stored a DBRef in a
The DBRef in this example points to a document in the NoteThe order of fields in the DBRef matters, and you must use the above sequence when using a DBRef.
In most cases you should use the manual reference method for connecting two or more related documents. However, if you need to reference documents from multiple collections, consider using DBRefs. |