MongoDB 聚合 - 从另一个集合中的值替换集合中的字段

时间:2021-03-15 15:17:04

标签: mongodb aggregation-framework

所以我有一个这样的收藏

_id: "a6c67aad-e90c-4a13-aae0-74e5ca5c8632"
value : true

还有这样的

_id: "a6c67aad-e90c-4a13-aae0-74e5ca5c8632"
otherValue : false

如何使用聚合管道根据 otherValue 使用第一个集合中的 value 更新第二个集合 _id

我试过使用查找然后像这样放松

{
  from: 'col1', 
  localField: 'otherValue', 
  foreignField: 'value', 
  as: 'data'
}

然后放松

{
  path: '$val'
}

但我不太确定从哪里开始,任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

试试这个:

db.collection1.aggregate([
    {
        $lookup: {
            from: "collection2",
            let: { c1_id: "$_id", value: "$value" },
            pipeline: [
                {
                    $match: {
                        $expr: { $eq: ["$_id", "$$c1_id"] }
                    }
                },
                {
                    $addFields: { otherValue: "$$value" }
                }
            ],
            as: "data"
        }
    },
    {
        $unwind: "$data"
    }
])

输出:

{
    "_id" : "a6c67aad-e90c-4a13-aae0-74e5ca5c8632",
    "value" : true,
    "data" : {
        "_id" : "a6c67aad-e90c-4a13-aae0-74e5ca5c8632",
        "otherValue" : true
    }
}

collection1 在哪里:

{
    "_id" : "a6c67aad-e90c-4a13-aae0-74e5ca5c8632",
    "value" : true
}

collection2 在哪里:

{
    "_id" : "a6c67aad-e90c-4a13-aae0-74e5ca5c8632",
    "otherValue" : false
}

答案 1 :(得分:0)

您可以使用 $merge 聚合阶段。

  • 匹配要用于更新第二个集合的源集合中的文档。
  • 从第二个集合中查找匹配的文档
  • 展开使其成为单个文档而不是数组(此阶段还消除了与第二个集合中不匹配的文档)
  • addFields 将第一个文档中的值存储到查找的文档中
  • 将Root替换为修改后的查找文档
  • 将修改后的文档与原始集合合并,匹配_id
db.collection.aggregate([
  {$match: { filter to pick the documents }},
  {$lookup: {
       from: "otherCollection"
       localField: "_id",
       foreignField: "_id",
       as: "otherDocument"
  }},
  {$unwind: "$otherDocument"},
  {$addFields:{
       "otherDocument.otherValue": "$value"
  }},
  {$replaceRoot: {newRoot: "$otherDocument"}},
  {$merge: {
       into: "otherCollection", 
       on: "_id", 
       whenMatched: "replace", 
       whenNotMatched: "insert" 
  }}
])
相关问题