MongoDB:如何在客户端解析DBRef?

时间:2016-06-13 15:36:34

标签: node.js mongodb aggregation-framework

我是mongodb的新手,很抱歉,如果这个问题很愚蠢:我已经提取了一份文件如下:

{
"_id" : ObjectId("575df70512a1aa0adbc2b496"),
"name" : "something",
"content" : {
    "product" : {
        "$ref" : "products",
        "$id" : ObjectId("575ded1012a1aa0adbc2b394"),
        "$db" : "mdb"
    },
    "client" : {
        "$ref" : "clients",
        "$id" : ObjectId("575ded1012a1aa0adbc2b567"),
        "$db" : "mdb"
    }
}

我指的是productsclients集合中的文档。我已经读过可以在客户端(https://stackoverflow.com/a/4067227/1114975)解析这些DBRef。

我该怎么做?我想避免查询这些对象并将它们嵌入到文档中。谢谢

2 个答案:

答案 0 :(得分:2)

您可以使用 $lookup 运算符解决此问题。请考虑以下聚合管道:

// Execute aggregate, notice the pipeline is expressed as an Array
collection.aggregate([
    {
        "$lookup": {
            "from": "product",
            "localField": "content.product.$id",
            "foreignField": "_id",
            "as": "products"
        }
    },
    {
        "$lookup": {
            "from": "clients",
            "localField": "content.client.$id",
            "foreignField": "_id",
            "as": "clients"
        }
    },
  ], function(err, result) {
    console.log(result);
});

答案 1 :(得分:1)

我会考虑使用Mongoose来帮助您解决这个问题和其他问题。在这种情况下,您可以使用以下内容:

Collection.find({}).populate('products').populate('clients')
          .exec(function(err, books) {...});

Mongoose populate