更新文档mongodb中的所有子文档

编程入门 行业动态 更新时间:2024-10-22 20:31:58
本文介绍了更新文档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中的所有子文档

本文发布于:2023-11-28 10:11:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641980.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文档   mongodb

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!