如何在mongodb中更新嵌套对象的字段? [英] how to update fields of a nested object in mongodb?
问题描述
萨拉姆(表示你好):)
Salam (means Hello) :)
我正在使用 node-mongodb-native 驱动程序,我需要更新特定的驱动程序存储在数组中的对象的字段.这是我的mongodb集合中的示例文档:
I'm using node-mongodb-native driver and I need to update specific fields of objects stored in an array. this is a sample document in my mongodb collection:
{
"fields" : [
{
"en" : "birthDate",
"status" : "enable",
"index" : 10
},{
"en" : "email",
"status" : "enable",
"index" : 4
},{
"en" : "inviterCode",
"status" : "enable",
"index" : 2
}
]
}
这是我的新数据:
var newData = [
{
"en" : "birthDate",
"status" : "disable",
},{
"en" : "email",
"status" : "disable",
}
];
如您所见
,如果en
字段匹配,则应更新status
字段.我知道以下查询适用于单个更新,但是如何通过单个查询实现多个更新?
as you can see, if en
field matches, status
field should be updated. I know that following query works for a single update, but how can I achieve multiple updates with a single query?
collection.update(
{'fields.en': 'birthDate'},
{$set:{'fields.$.status': 'disable'}},
{w:1, multi: true},
function(error, count){
}
);
推荐答案
不幸的是,使用单个更新是不可能的.在MongoDB上有一个公开票证.
It is unfortunately not possible using a single update. There is a open ticket over at MongoDB for this.
目前,您需要以编程方式执行此操作(例如,遍历数组以找到相关的索引).
For now you would need to do this programatically (e.g. looping through the array to find the relevant indexes).
这篇关于如何在mongodb中更新嵌套对象的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!