1

Can I update all the subdocuments in array matching my update query? Here is example of collection elements:

{
    x: 1,
    myarray: [
        {
           a: 1,
           b: 2,
        },
        {
           a: 1,
           b: 4,
        }  
    ]
}

Then I write query like this:

    MyModel.update({x: 1, myarray.a: 1}, 
                   {$set: 
                      {"myarray.$.b": 3}
                   },
                   function(err) {
    });

It updates only the first subdocument in myarray. In the documentation it is written that this kind of queries update only the first document. I want to know if there is a way to update all matching subdocuments in array. Thanks in advance.

Edgar
  • 1,143
  • 10
  • 12

1 Answers1

1

You currently can't do that with the positional operator and there is a JIRA for this. However, a workaound is to loop through each matched document and within that document, loop through the array updating the matched element:

db.collection.find({"x": 1, "myarray.a": 1}).forEach(function(doc) {
    doc.myarray.forEach(function(item){
        if(item.a == 1){
            item.b = 3;
        }
    });
    db.collection.save(doc);
});
chridam
  • 100,957
  • 23
  • 236
  • 235
  • But aren't there another way which include query ? not loop – Edgar Mar 30 '15 at 13:01
  • Apart from the looping update you can read the document, edit manually and save it replacing the older one making sure you avoid any race conditions by [**updating if current**](http://docs.mongodb.org/manual/tutorial/update-if-current/). You can vote for the [**JIRA**](https://jira.mongodb.org/browse/SERVER-1243) issue if you want to see this addressed/incorporated in the next releases. – chridam Mar 30 '15 at 13:08