2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

how to update multiple array elements in mongodb

I have a mongo document which holds an array of elements.
I"d like to reset the handled attribute in the array where profile = XX. The document is in the following form:
 {   

"_id" : ObjectId("4d2d8deff4e6c1d71fc29a07"),   

"user_id" : "714638ba-2e08-2168-2b99-00002f3d43c0",   

"events" : [           

{                    "handled" : 1, "profile" : 10,"data" : "....."

}           

{                     "handled" : 1,"profile" : 10,"data" : "....."           

}           

{                    "handled" : 1,"profile" : 20,"data" : "....."           

}            ...       ]}

so, I tried the following:
.update({"events.profile":10},{$set:{"events.$.handled":0}},false,true)

however it updates only the first matched array element. (that"s the defined behavior for $ - the positional operator)
Any idea how to update all matched array elements?

userimage

At this moment it is not possible to use the positional operator to update all items in an array. See JIRA http://jira.mongodb.org/browse/SERVER-1243

As a work around you can:

  • Update each item individually (events.0.handled events.1.handled ...) or...
  • Read the document, do the edits manually and save it replacing the older one (check "Update if Current" if you want to ensure atomic updates)
Answer is