对多级子文档使用位置运算符 [英] Using positional operator for multiple levels of subdocuments
本文介绍了对多级子文档使用位置运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 mongodb 中使用子文档.
I am using sub-documents in mongodb.
通过一级子文档,我可以更新文档
With one level of sub-documents, I can update documents with
Parent.findOneAndUpdate({ _id: parentId, 'children._id': childId }, {
$set: {
'children.$.name': name
}
}, (err, doc) => {
...
});
但是我在对另一层子文档做同样的事情时遇到了问题,即
but I have problems doing the same for another level of sub-documents, i.e.
Parent.findOneAndUpdate({ _id: parentId, 'children._id': childId, 'children.grandchildren._id': grandchildId }, {
$set: {
'children.$.grandchildren.$.name': name
}
}, (err, doc) => {
...
});
位置运算符 ($
) 是否仅限于 1 级子文档?
Is the positional operator ($
) limited to only 1 level of subdocuments?
推荐答案
位置运算符 ($) 仅支持一个级别,也支持第一个匹配元素.作为一种解决方法,您可以这样做,
Positional Operator ($) only supports one level and also the first matching element. As a workaround what you can do is this,
$set: {'children.$.grandchildren.0.name':名字}
我认为这个问题在这里有更清楚的解释
这篇关于对多级子文档使用位置运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文