MongoDB:使用字典更新数组中的文档 [英] MongoDB: Updating document in array with dictionary
问题描述
我发现了一个 StackOverflow 问题,非常接近回答我的问题,但不完全是这样.
I found a StackOverflow Question that comes very close to answering my question, but not quite there.
接受这个原始问题(修改数组中的文档),但假设您没有想要进行的特定更改.相反,我有一本我希望进行更改的字典.下面是一个例子:
Take this original question (modifying a document that is in an array) but assume that you do not have a specific change you wish to make. Instead, I have a dictionary of changes that I wish to make. Here is an example:
原始文档
{
_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驱动谢谢
How can I apply this dictionary of changes to John (id:2)? Incase it is relevant, I am using the MongoDB-Node.JS Driver Thank you
推荐答案
就像在您引用的问题中一样,您需要使用 $
位置运算符,但在这种情况下使用 update
:
Just like in the question you referenced, you need to use the $
positional operator, but with update
in this case:
collection.update({_id:something, 'recipients.id': 2}, {$set: {'recipients.$': {
isread: true,
fullname: 'jonathan'
}}}, function (err) {...
编辑
要不替换整个数组元素对象,您必须执行以下操作:
To not replace the whole array element object you'd have to do something like this:
collection.update({_id:something, 'recipients.id': 2}, {$set: {
'recipients.$.isread': true,
'recipients.$.fullname': 'jonathan'
}}, function (err) {...
这篇关于MongoDB:使用字典更新数组中的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!