猫鼬更新子文档数组

编程入门 行业动态 更新时间:2024-10-19 21:22:19
本文介绍了猫鼬更新子文档数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我可以更新匹配更新查询的数组中的所有子文档吗?这是集合元素的示例:

Can I update all the subdocuments in array matching my update query? Here is example of collection elements:

{ x: 1, myarray: [ { a: 1, b: 2, }, { a: 1, b: 4, } ] }

然后我这样写查询:

MyModel.update({x: 1, myarray.a: 1}, {$set: {"myarray.$.b": 3} }, function(err) { });

它仅更新myarray中的 first 子文档.在文档中写道,这种查询仅更新第一个文档.我想知道是否有一种方法可以更新数组中所有匹配的子文档.预先感谢.

It updates only the first subdocument in myarray. In the documentation it is written that this kind of queries update only the first document. I want to know if there is a way to update all matching subdocuments in array. Thanks in advance.

推荐答案

您目前无法使用 位置运算符 ,其中有一个 JIRA .但是,一种解决方法是遍历每个匹配的文档,并在该文档内遍历整个数组,以更新匹配的元素:

You currently can't do that with the positional operator and there is a JIRA for this. However, a workaound is to loop through each matched document and within that document, loop through the array updating the matched element:

db.collection.find({"x": 1, "myarray.a": 1}).forEach(function(doc) { doc.myarray.forEach(function(item){ if(item.a == 1){ item.b = 3; } }); db.collection.save(doc); });

更多推荐

猫鼬更新子文档数组

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

发布评论

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

>www.elefans.com

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