Mongodb 简明教程
MongoDB - Database References
如 MongoDB 关系的最后一章中所述,为了在 MongoDB 中实现规范化的数据库结构,我们使用了称为 Referenced Relationships (在中也称为 Manual References )的概念,其中我们手动存储其他文档 ID 被引用的文档。但是,如果一份文档包含来自不同集合的引用,则我们可以使用 MongoDB DBRefs 。
As seen in the last chapter of MongoDB relationships, to implement a normalized database structure in MongoDB, we use the concept of Referenced Relationships also referred to as Manual References in which we manually store the referenced document’s id inside other document. However, in cases where a document contains references from different collections, we can use MongoDB DBRefs.
DBRefs vs Manual References
作为示例场景,我们在其中使用 DBRefs 而不是手动引用,考虑一个数据库,其中我们在不同的集合(address_home、address_office、address_mailing 等)中存储不同类型的地址(家庭、办公室、邮件等)。现在,当 user 集合的文档引用地址时,它还需要根据地址类型指定要查找的集合。在文档引用来自多个集合的文档的此类场景中,我们应该使用 DBRefs。
As an example scenario, where we would use DBRefs instead of manual references, consider a database where we are storing different types of addresses (home, office, mailing, etc.) in different collections (address_home, address_office, address_mailing, etc). Now, when a user collection’s document references an address, it also needs to specify which collection to look into based on the address type. In such scenarios where a document references documents from many collections, we should use DBRefs.
Using DBRefs
DBRefs 中有三个字段 −
There are three fields in DBRefs −
-
$ref − This field specifies the collection of the referenced document
-
$id − This field specifies the _id field of the referenced document
-
$db − This is an optional field and contains the name of the database in which the referenced document lies
考虑一个示例用户文档,其中 DBRef 字段 address ,如代码片段所示 −
Consider a sample user document having DBRef field address as shown in the code snippet −
{
"_id":ObjectId("53402597d852426020000002"),
"address": {
"$ref": "address_home",
"$id": ObjectId("534009e4d852427820000002"),
"$db": "tutorialspoint"},
"contact": "987654321",
"dob": "01-01-1991",
"name": "Tom Benzamin"
}
address 此处的 DBRef 字段指定引用的地址文档位于 address_home 数据库下的 tutorialspoint 集合中,并且 ID 为 534009e4d852427820000002。
The address DBRef field here specifies that the referenced address document lies in address_home collection under tutorialspoint database and has an id of 534009e4d852427820000002.
以下代码根据 $ref 参数(在我们的示例中为 address_home )指定的集合中动态查找文档,其中 ID 为 DBRef 中的 $id 参数指定。
The following code dynamically looks in the collection specified by $ref parameter (address_home in our case) for a document with id as specified by $id parameter in DBRef.
>var user = db.users.findOne({"name":"Tom Benzamin"})
>var dbRef = user.address
>db[dbRef.$ref].findOne({"_id":(dbRef.$id)})
上面的代码返回存在于 address_home 集合中的以下地址文档 −
The above code returns the following address document present in address_home collection −
{
"_id" : ObjectId("534009e4d852427820000002"),
"building" : "22 A, Indiana Apt",
"pincode" : 123456,
"city" : "Los Angeles",
"state" : "California"
}