MongoDb-如何使用$ set更新嵌套对象的多个元素? [英] MongoDb - How can I update multiple elements of a nested object using $set?
问题描述
可以说我有以下文件:
{name: 'myDoc', nestedDoc: {a: 1, b: 2, c: 3}}
我想与nestedDoc合并一个新对象:
And I would like to merge with the nestedDoc a new object:
{b: 20, c:30, d:40}
因此生成的对象将是:
{name: 'myDoc', nestedDoc: {a: 1, b: 20, c: 30, d: 40}}
如何在单个查询中执行此操作?我觉得我需要多个$ set调用,但是对象属性名称必须是唯一的.换句话说,我希望可以执行以下操作:
How can I go about doing this in a single query? I feel like I need multiple $set calls however object property names must be unique. In other words, I wish I could do the following:
db.myCollection.update({name: 'myDoc', nestedDoc: {$set: {b: 20}, $set: {c: 30}, $set: {d: 40}});
一些额外的细节是MongoDB版本是1.8.2,而我使用的是NodeJS节点本机驱动程序.
Some extra details are that the MongoDB version is 1.8.2 and I am using the NodeJS node-native driver.
推荐答案
您可以使用以下内容进行更新:
You can update by using the following:
db.myCollection.update({
name: 'mydoc'
}, {
$set: {
'nestedDoc.b': 20,
'nestedDoc.c': 30,
'nestedDoc.d': 40
}
})
这里是有关update命令的更多信息: http://www.mongodb.org/display/DOCS/Updating#Updating
Here is more information about update command: http://www.mongodb.org/display/DOCS/Updating#Updating
这篇关于MongoDb-如何使用$ set更新嵌套对象的多个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!