更新文档mongodb中的所有子文档 [英] Update all sub-documents inside document mongodb

查看:445
本文介绍了更新文档mongodb中的所有子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要这样的东西

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?

推荐答案

您不能使用单个mongodb查询来更新文档中数组的所有元素,您可以根据需要使用以下代码

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

这篇关于更新文档mongodb中的所有子文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆