BlaShadow
BlaShadow

Reputation: 11693

Update all sub-documents inside document mongodb

I want something like this

db.students.update( 
    { "_id": 4, "grades.grade": 85 }, 
    { 
        "$set": { "grades.$.std" : 6 } 
    } 
)

But I want to update all "grades" not just the first one, like the $ explain

when I tried it just update the first one. any ideas about to update the entire list?

Upvotes: 1

Views: 1415

Answers (3)

Sudhakar Reddy
Sudhakar Reddy

Reputation: 348

My answer is too late here but it helps others who facing this issue. Please look into this JIRA thread it has stated you can update all matching documents: https://jira.mongodb.org/browse/SERVER-1243

Upvotes: 0

Saheed Hussain
Saheed Hussain

Reputation: 1158

You can't update all the elements of an array in a document using a single mongodb query, you can use following code for your purpose

db.students.find({"grades.grade": 85 }).forEach(function(item){ 
    //iterate over matched docs
    item.grades.forEach(function(c){ //iterate over array element in the current doc
        if(c.grade==85){
             c.std=6;
        }
    });

    db.students.save(item);
});

Upvotes: 4

Neil Lunn
Neil Lunn

Reputation: 151112

I'll offer a longer explanation than a comment and a current lack of searching that turns up anything more than a reference to a feature request in JIRA.

So as the documentation for positional $ operator says, you only get the first match, and this is currently how things work by design.

Probably your best approach is to keep issuing the same update until the response from the write concern result says that nothing was actually updated. That will in each turn set every element that matches in your array to the desired value.

Otherwise, pull the entire document with a find request, alter the required elements in the array in code and then save it back.

Vote up the referenced feature request and cross your fingers that someone finds it important enough to include in a near future release. But there is no method otherwise to allow you do to this.

NOTE: The feature request is currently four years old so I would not be holding my breath for it to happen.

Upvotes: 1

Related Questions