Update document in array , always updating first element

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 : Mongo playground

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:

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 link in tldr at top
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

Hi @Aditya_Patil2 and welcome to the community!!

The query parameter inside the db.collection.update() command, searches for the correct document and later applies the $set to the required field.

The following query would resolve the above issue:

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

Please refer to the arrayFilters documentation for more information.

Also, the $arrayFilters is available since MongoDB version 3.6. If you are looking to use the above query, would recommend you to update to the required version.

Let us know if you have any more questions.

Thanks
Aasawari

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.