我可以更新匹配更新查询的数组中的所有子文档吗?这是集合元素的示例:
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); });更多推荐
猫鼬更新子文档数组
发布评论