繁体   English   中英

如何对对象列表中的每个字段执行 MongoDB 聚合查找查询

[英]How to perform MongoDB aggregate lookup query for each field in a list of objects

我有看起来像这样的文件:

{
    "_id": ObjectId("Some Value"),
    "example_list" : [
        {
            "external_id" : ObjectId("Some Value1"),
            "other" : "stuff"
        },
        {
            "external_id" : ObjectId("Some Value2"),
            "other" : "stuff"
        },
        {
            "external_id" : ObjectId("Some Value3"),
            "other" : "stuff"
        }
    ]
}

我想从名为example_collection的集合中为example_list中的每个 object 解析external_id (使用查找),以便 output 类似于:

{
    "_id": ObjectId("Some Value"),
    "example_list" : [
        {
            "external_id" : ObjectId("Some Value1"),
            "other" : "stuff",
            "external_data" : "data1 retrieved from lookup"
        },
        {
            "external_id" : ObjectId("Some Value2"),
            "other" : "stuff",
            "external_data" : "data2 retrieved from lookup"
        },
        {
            "external_id" : ObjectId("Some Value3"),
            "other" : "stuff",
            "external_data" : "data3 retrieved from lookup"
        }
    ]
}

如何使用聚合管道完成此操作? 我知道如何查找,但不知道如何遍历列表中的每个 object 并插入回 object。

一种选择是:

db.example_lists.aggregate([
  {$lookup: {
      from: "example_collection",
      localField: "example_list.external_id",
      foreignField: "_id",
      as: "example_list2"
  }},
  {
    $set: {
      example_list2: "$$REMOVE",
      example_list: {$map: {
          input: "$example_list",
          in: {$mergeObjects: [
              "$$this",
              {$arrayElemAt: [
                  "$example_list2",
                  {$indexOfArray: ["$example_list2._id", "$$this.external_id"]}
                ]
              }
            ]
          }
        }
      }
    }
  }
])

看看它在操场上的例子是如何工作的

如果要从结果中删除external_id ,可以在中间添加$map步骤:

{$set: {
     example_list: {
       $map: {
         input: "$example_list",
         in: {_id: "$$this.external_id", other: "$$this.other"}
       }
     }
   }
 },

看看它在操场上的例子是如何工作的

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM