Home > Enterprise >  How to update multiple objects in the array in mongoDB?
How to update multiple objects in the array in mongoDB?

Time:09-28

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 },
    ],
  },
];

CodePudding user response:

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.

  • Related