更新文档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);
});