Home > Back-end >  MongoDB updating array of objects does not work as expected
MongoDB updating array of objects does not work as expected

Time:10-08

Got multiple documents in a db one of which looks like this:

{
   "searchWord":[
      "pizz",
      "pizza"
   ],
   "result":[
      {
         "idMeal":1,
         "strMeal":"test1",
         "strInstructions":"test1"
      },
      {
         "idMeal":2,
         "strMeal":"test2",
         "strInstructions":"test2"
      }
   ]
}

Tried to solve it like this:

eg:

 db.meals.updateOne(
    {
      "searchWord": "pizz",
      "result": { $elemMatch: { idMeal: "1"  } }
    },
    { $set: { 'result.$.strMeal' : "UPDATED" } }
 )

This doesnt update the respective subdocument only the 2nd as if I wrote

{ $set: { 'result.1.strMeal' : "UPDATED" } }

(Which will result in the 2nd subdocument being updated)

This is the other idea (Same result)

db.meals.updateOne(
  { searchWord: "pizz", 'result.idMeal': 319012 },
  { $set: { "result.$.strMeal" : "fsdf" } }
)

What I dont seem to understand is its exactly the syntax that is provided by mongo yet it doesnt work

The "$" operator doesnt pick up which array of objects I wanna update

CodePudding user response:

Try to use $[] in your $set for multiple positional element

db.collection.update({
  "searchWord": "pizz"
},
{
  $set: {
    "result.$[r].strMeal": "UPDATED"
  }
},
{
  arrayFilters: [
    {
      "r.idMeal": 1
    }
  ]
})

Here is the Mongo playground for your reference.

  • Related