从其他字段更新 mongo 数组元素字段

Update mongo array elements field from its other field

让我们假设以下文档

{
    "companies": [
        {"id": 1, "name": "Company 1", "new_name": "New company 1"},
        {"id": 2, "name": "Company 2", "new_name": "New company 2"}
    ]
}

有没有一种方法可以让我自己引用数组元素以迁移到方案

{
    "companies": [
        {"id": 1, "name": "New company 1", "new_name": "New company 1"},
        {"id": 2, "name": "New company 2", "new_name": "New company 2"}
    ]
}

在 mongo 4.2 中没有使用 forEach 编写脚本的情况下对 update 的单次调用? 像

update(
...
{
  "companies.$[].name": "$companies.<???>.new_name"
}
)

要在查询中访问另一个字段的值,您需要使用聚合,利用在 MongoDB 版本 4.2 中引入的 .update() 中的执行聚合管道,尝试以下查询:

update(
    ...
    [
        {
          $addFields: { // will replace existing field with new value
            companies: {
              $map: { // Iterates on an array & creates a new one
                input: "$companies",
                in: { $mergeObjects: [ "$$this", { name: "$$this.new_name" } ] } // `mergeObjects` will merge two objects `name` field will be replace in current object i.e; `$$this`
              }
            }
          }
        }
      ]
    )

测试: 您可以在此处测试聚合管道:mongoplayground

注意: 似乎使用聚合是在一次调用中执行此操作的唯一选项,但只有当您的数组太大时才会出现缺点,因为 $map必须再次重写整个数组。