Update all sub-documents inside document mongodb

亡梦爱人 提交于 2019-12-11 10:03:24

问题


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?


回答1:


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);
});



回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/23400845/update-all-sub-documents-inside-document-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!