我想知道如何为所有嵌套文档设置属性。
假设我有一个具有嵌套category文档的item文档:
{
items: [
{
hidden: true
},
{
hidden: true
},
...
]
}如何将项的所有hidden属性更新为false
我试过这样做:
db.categories.update({}, {$set: {'items.$.hidden': false}})但是MongoDB给了我The positional operator did not find the match needed from the query. Unexpanded update: items.$.hidden。有什么建议吗?
发布于 2015-06-25 08:42:27
由于本期,您需要使用脚本进行更新
使用以下方法更新所有字段:
db.collection.find({
_id: ObjectId("558bbd23fdf0f33ec7a067c8")
}).forEach(function(doc) {
doc.items.forEach(function(items) {
if (items.hidden == true) {
items.hidden = false;
}
});
db.collection.save(doc);
});发布于 2015-06-25 08:43:14
您可以尝试以下更新,它使用游标方法forEach()来迭代游标和访问文档,获取items数组并在其上循环并修改hidden字段,如下面的示例所示:
db.test.insert([
{
"_id" : 1,
"items" : [
{
"_id" : 1,
"hidden" : true
},
{
"_id" : 2,
"hidden" : true
}
]
},
{
"_id" : 2,
"items" : [
{
"_id" : 1,
"hidden" : true
},
{
"_id" : 2,
"hidden" : true
}
]
}
])
db.test.find().forEach(function (doc){
var items = [];
doc.items.forEach(function (item){
item.hidden = false;
items.push(item);
});
doc.items = items;
db.test.save(doc);
});发布于 2015-06-25 08:47:59
https://stackoverflow.com/questions/31045094
复制相似问题