2

TL;DR : Updating element in array always results in first element updated and results differ based on property name of key used in find params Playground : https://mongoplayground.net/p/-4kGZnxa-WA

I want to update an object in a array and I am using 2 of the object properties to find the object then using $set operator with array.$.updateProperty to update the object

Here is the working playground link of what I want to do: https://mongoplayground.net/p/dswt8vuzJMc

But I cant reproduce the same when I change a single property name (both in database as well as find parameter) , from the above example I changed property foo to trackID but then only the first element in array is always updated

Playground : https://mongoplayground.net/p/-4kGZnxa-WA

It seems weird as I assumed the property name shouldn't matter as long as it used the same in find params too and its not a keyword like _id

1 Answer 1

2

Your update is very close. You need to use "$elemMatch" to identify the specific array position where both conditions match.

N.B.: $ will only update the first matching array element. If you want to update all array elements, use $[], and if you want to update all matching array elements, using "arrayFilters" with $[<indentifier>] is convenient.

db.collection.update({
  "_id": ObjectId("62f11e22d99c79532de6ff7f"),
  "jobs": {
    "$elemMatch": {
      "trackID": 0,
      "name": "kaisen_track-0_h264_1080p"
    }
  }
},
{
  "$set": {
    "jobs.$.status": "Done"
  }
})

Try it on mongoplayground.net.

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

3 Comments

Thanks , works perfect but I am still confused why did the operation worked on this playground (working playground mentioned in question): mongoplayground.net/p/dswt8vuzJMc The only difference I see with both the playgrounds in question is the property name , am I missing any other difference ?
@Solaris I'm a little confused too. I don't know the internals of mongod so I can only speculate. By some means (?), in your original query ,mongod determines the array element of each match independently (?) and if they both happen to be the same, then $ works as a valid array position? It's actually a little scary since if the mongoplayground prototyping worked (by some lucky/unlucky occurrence), there's no guarantee (unlikely really) that the luck would carry over to your real/production system. That's why learning the proper query syntax, here "$elemMatch", is so important.
Might be a bug or unhandled checks on necessary syntax , anyhow the proper syntax $elemMatch is working consistently as expected so will stick to it, thanks for the help

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.