简体   繁体   中英

How to update multiple objects in the array in mongoDB?

How to update multiple objects in the array in MongoDB? Assume that I am retrieving from the client an array of titles that need to be changed.

Example:

Data from client:

[0,3]

Document in the MongoDB:

[
  {
    _id: 0,
    dishes: [
      { title: 0, in_stock: true },
      { title: 1, in_stock: false },
      { title: 2, in_stock: true },
      { title: 3, in_stock: false },
    ],
  },
];

The result should be:

[
  {
    _id: 0,
    dishes: [
      { title: 0, in_stock: false },
      { title: 1, in_stock: false },
      { title: 2, in_stock: true },
      { title: 3, in_stock: true },
    ],
  },
];

You can simply put a aggregation pipeline in your update clause.

db.collection.update({},
[
  {
    "$addFields": {
      "dishes": {
        "$map": {
          "input": "$dishes",
          "as": "d",
          "in": {
            "$cond": {
              "if": {
                "$in": [
                  "$$d.title",
                  [
                    0,
                    3
                  ]
                ]
              },
              "then": {
                title: "$$d.title",
                in_stock: {
                  "$not": [
                    "$$d.in_stock"
                  ]
                }
              },
              "else": "$$d"
            }
          }
        }
      }
    }
  }
])

Here is the Mongo playground for your reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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