我找到了StackOverflow Question这非常接近回答我的问题,但还不够。
回答这个原始问题(修改数组中的文档),但假设您没有希望进行的特定更改。相反,我有一本我希望进行的更改的字典。这是一个例子:
原始文档
{
_id: something,
recipients: [{id:1, name:"Andrey", isread:false}, {id:2, name:"John", isread:false}]
}
要进行的更改
{
isread: true,
fullname: 'jonathan'
}
如何将这本更改字典应用到 John (id:2)? 如果相关,我正在使用 MongoDB-Node.JS Driver 谢谢
最佳答案
就像您引用的问题一样,您需要使用 $
positional operator ,但在本例中使用 update
:
collection.update({_id:something, 'recipients.id': 2}, {$set: {'recipients.$': {
isread: true,
fullname: 'jonathan'
}}}, function (err) {...
编辑
要不替换整个数组元素对象,您必须执行以下操作:
collection.update({_id:something, 'recipients.id': 2}, {$set: {
'recipients.$.isread': true,
'recipients.$.fullname': 'jonathan'
}}, function (err) {...
关于node.js - MongoDB:用字典更新数组中的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11871238/