使用另一个字段的值更新 MongoDB 数组字段值

时间:2021-06-01 10:50:44

标签: mongodb

我知道可以更新特定的数组元素,如此处所述: https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/

此外,我知道可以使用字段值来更新另一个字段的值,如下所述:Update MongoDB field using value of another field

我需要的是两者的结合。

假设我在数据库中有这个:

{
  a: [
     {
        aa: 10
     },
     {
        cc: 15
     }

  ]
}

现在,我想将字段 bb 添加到具有 aa 值的数组文档中,但前提是 aa 存在。所以输出是:

{
  a: [
     {
        aa: 10,
        bb: 10
     },
     {
        cc: 15
     }

  ]
}

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

从 MongoDB 4.2 开始尝试 update with aggregation pipeline

  • 匹配字段存在条件
  • $map 迭代 a 数组的循环
  • $cond 检查条件,如果 aa 字段不为空,则添加值为 bb 的新字段 aa 并使用 $mergeObjects 与当前对象合并,否则返回当前对象
db.collection.update(
  { "a.aa": { $exists: true } },
  [{
    $set: {
      a: {
        $map: {
          input: "$a",
          in: {
            $cond: [
              { $ne: ["$$this.aa", null] },
              { $mergeObjects: ["$$this", { bb: "$$this.aa" }] }
              "$$this",
            ]
          }
        }
      }
    }
  }],
  { multi: true }
)

Playground