1

I am trying to update multiple nested documents in a document in mongoDB.

Say my data is:

{
    "_id" : "ObjectId(7df78ad8902c)",
    "title" : "Test",
    "img_url" : "[{s: 1, v:1}, {s: 2, v: 2}, {s: 3, v: 3}]",
    "tags" : "['mongodb', 'database', 'NoSQL']",
    "likes" : "100"
}

I want to update v to 200 for s = 1 and s= 2 in img_url list. It is easy to update v for any single s.

Is there any way to update multiple documents satisfying some criteria.

I tried:

db.test.update({ "_id" : ObjectId("7df78ad8902c"), "img_url.s": {$in : ["1", "2"]}}, {$set: { "img_url.$.v" : 200 } });
and 
db.test.update({ "_id" : ObjectId("7df78ad8902c"), "img_url.s": {$in : ["1", "2"]}}, {$set: { "img_url.$.v" : 200 } }, {mulit: true});

Some sources are suggesting it is not possible to do so.

Multiple update of embedded documents' properties

https://jira.mongodb.org/browse/SERVER-1243

Am I missing something ?

Community
  • 1
  • 1
Geek_To_Learn
  • 1,816
  • 5
  • 28
  • 48
  • Possible duplicate of [How to change all the array elements in a mongodb document to a certain value?](http://stackoverflow.com/questions/32610663/how-to-change-all-the-array-elements-in-a-mongodb-document-to-a-certain-value) – styvane Jan 15 '16 at 08:16

1 Answers1

0

For the specific case/example you have here. You are specifying an _id which means you are to update only one with that specific _id.

to update img_url try without the _id; something like this:

db.test.update({}, {"$set":{"img_url.0":{s:1, v:400}}}, {multi:true})
db.test.update({}, {"$set":{"img_url.1":{s:2, v:400}}}, {multi:true})

0 and 1 in img_url are the array indexes for s:1 and s:2

in order to update based on specific criteria you need to set the attribute you need on the first argument. say for example, to update all documents that have likes greater than 100 increment by 1 you do (assuming likes type is int...):

db.people.update( { likes: {$gt:100} }, {$inc :{likes: 1}}, {multi: true} )

hope that helps

ibininja
  • 1,209
  • 1
  • 15
  • 29