0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.