如何在 MongoDB 中有条件地更新每个子文档?

问题描述 投票:0回答:1
{
  _id: ObjectId(),
  animals: [
    { type: "dog", IQ: 100  }, 
    { type: "cat", IQ: 110  }, 
    { type: "bear", IQ: 120  }, 
    ...
  ]
}

如何写一个updateOne语句,根据子文档的

animals
字段,有条件地更新
type
字段的每个子文档的IQ字段?

例如,

如果

type === "dog"
,则将智商更新为200,但如果
type === "cat"
,则将智商更新为300,以此类推

javascript node.js mongodb mongodb-query aggregation-framework
1个回答
1
投票

您可以像这样使用流水线形式的更新:

db.collection.update({},
[
  {
    "$set": {
      "animals": {
        "$map": {
          "input": "$animals",
          "in": {
            "$switch": {
              "branches": [
                {
                  "case": {
                    "$eq": [
                      "$$this.type",
                      "dog"
                    ]
                  },
                  "then": {
                    type: "dog",
                    IQ: 200
                  }
                },
                {
                  "case": {
                    "$eq": [
                      "$$this.type",
                      "cat"
                    ]
                  },
                  "then": {
                    type: "cat",
                    IQ: 300
                  }
                }
              ],
              default: "$$this"
            }
          }
        }
      }
    }
  }
])

使用

$map
遍历数组,并使用
$switch
有条件地设置 IQ。 游乐场链接。

© www.soinside.com 2019 - 2024. All rights reserved.