【问题标题】:MongoDb Post formatting of $lookup aggregation with limited data数据有限的 $lookup 聚合的 MongoDb Post 格式
【发布时间】:2018-02-01 19:36:25
【问题描述】:

我有 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":{---}}

【问题讨论】:

  • 使用$replaceRoot 或简单的$project 字段返回子属性“之后”执行$unwind。将$project 放置在“之前”并没有真正获得太多收益,或者至少没有您认为的那么多收益。将$unwind 直接放在$lookup 之后实际上是pipeline optimization,它将$unwind“提升”为$lookup 本身。
  • 成功了。谢谢@NeilLunn
  • @NeilLunn $replaceRoot 有效,但 $project 无效。根据您的建议,我使用嵌入的文档值更改了 $unwind 和 $project 的顺序。但仍然无法摆脱格式 {"inventory_docs":{---}}。我现在正在使用这个查询: db.coll1.aggregate([ { $lookup: { from: "coll2", localField: "_id", foreignField: "comm_field", as: "inventory_docs" } }, { $unwind:" $inventory_docs"}, { $project:{"_id" : 0, "inventory_docs._id" : 1, "inventory_docs.comm_field" : 1, "inventory_docs.status" : 1}} ])

标签: mongodb aggregation-framework


【解决方案1】:

尼尔的回答奏效了。添加{ $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" } }
])

【讨论】:

    猜你喜欢
    • 2022-01-05
    • 1970-01-01
    • 2018-08-06
    • 2019-03-23
    • 1970-01-01
    • 2019-09-03
    • 2021-02-22
    • 1970-01-01
    • 2018-07-21
    相关资源
    最近更新 更多