MongoDb使用有限的数据格式化$ lookup聚合

时间:2017-08-24 04:11:22

标签: mongodb aggregation-framework

我有2个集合coll1和coll2。我想在字段“_id”和“comm_field”上应用$ lookup,所以我使用了查询:

db.coll1.aggregate([
    {
      $lookup:
        {
          from: "coll2",
          localField: "_id",
          foreignField: "comm_field",
          as: "inventory_docs"
        }
   },
   {
       $project:{"_id" : 0, "inventory_docs" : 1}
   },
   { $unwind:"$inventory_docs"}
])

输出为:

/* 1 */
{
    "inventory_docs" : {
        "_id" : ObjectId("ssdfsfsdfsdfsfsdfsdfsdfsfsdf"),
        "comm_field" : NumberLong(1111),
        "status" : "active"
    }
}

/* 2 */
{
    "inventory_docs" : {
        "_id" : ObjectId("erteterterterterterterterter"),
        "comm_field" : NumberLong(1111),
        "status" : "active"
    }
}

/* 3 */
{
    "inventory_docs" : {
        "_id" : ObjectId("vbvbfvbdbbcvbvcbcdrgvbcbcbcv"),
        "comm_field" : NumberLong(2222),
        "status" : "active"
    }
}

有什么方法可以让我看到输出:

        {
            "_id" : ObjectId("ssdfsfsdfsdfsfsdfsdfsdfsfsdf"),
            "comm_field" : NumberLong(1111),
            "status" : "active"
        }
        {
            "_id" : ObjectId("erteterterterterterterterter"),
            "comm_field" : NumberLong(1111),
            "status" : "active"
        }
        {
            "_id" : ObjectId("vbvbfvbdbbcvbvcbcdrgvbcbcbcv"),
            "comm_field" : NumberLong(2222),
            "status" : "active"
        }

基本上我希望我的输出格式为{---},而不是{“inventory_docs”:{---}}

1 个答案:

答案 0 :(得分:0)

尼尔的回答奏效了。增加{ $replaceRoot: { newRoot: "$inventory_docs" } }完成了这项工作。谢谢尼尔。

db.coll1.aggregate([
    {
      $lookup:
        {
          from: "coll2",
          localField: "_id",
          foreignField: "comm_field",
          as: "inventory_docs"
        }
   },
   {
       $project:{"_id" : 0, "inventory_docs" : 1}
   },
   { $unwind:"$inventory_docs"},
   { $replaceRoot: { newRoot: "$inventory_docs" } }
])