365Tools
    发布时间:2024-03-30 11:30:02
在《MongoDB关系》一节中,为了在 MongoDB 中实现规范化的数据库结构,我们使用了引用式关系(也称为手动引用)的概念,在手动引用中,我们需要将被引用文档的 _id 存储在其他文档中。当文档中需要引用来自不同集合数据的情况下,我们可以使用 MongoDB 中的 DBRefs。{ $ref : value, $id : value, $db : value }
DBRefs 中有以下三个字段:
{
    "_id" : ObjectId("603c93f2f2c28d0fdf74ae7b"),
    "phone" : "15011226666",
    "pincode" : "01-01-1991",
    "name" : "bianchengbang",
    "address": {
        "$ref": "address_home",
        "$id": ObjectId("603c9355f2c28d0fdf74ae79"),
        "$db": "bianchengbang"
    }
}
上面的 address 字段指定了引用的文档位于“bianchengbang”数据库下的“address_home”集合中,文档的 _id 值为 603c9355f2c28d0fdf74ae79。
> var user = db.users.findOne({"name":"bianchengbang"})
> var dbRef = user.address
> db[dbRef.$ref].findOne({"_id":(dbRef.$id)})
{
        "_id" : ObjectId("603c9355f2c28d0fdf74ae79"),
        "place" : "22 A, Indiana Apt",
        "postcode" : 123456,
        "city" : "Los Angeles",
        "country" : "California"
}
上面的示例代码中 $ref 参数指定了集合的名称(本例中是 address_home),并在其中动态查找 _id 为 DBRef 中 $id 参数指定的文档。