所以我在一个集合中有以下文件。
{
_id: "1",
quantity: 0,
array: [{name: "test1a", quantity: 10}, {name: "test1a", quantity: 1}, {name: "test1b", quantity: 10}, {name: "test1c", quantity: 1}]
}
{
_id: "2",
quantity: 0,
array: [{name: "test2a", quantity: 10}, {name: "test2b", quantity: 10}, {name: "test2c", quantity: 1}]
}
{
_id: "3",
quantity: 0,
array: [{name: "test3a", quantity: 10}, {name: "test3b", quantity: 10}, {name: "test3c", quantity: 1}]
}
我想要的是查询集合中的所有文档,其数组包含name =“test1a”的对象,并使用新值更新这些对象数量属性。
答案 0 :(得分:1)
尝试类似
的内容db.collection.find({"array.name": "test1a"}).forEach(function(doc){
var myArray = doc.array;
for (var i in myArray){
if(myArray[i].name == "test1a"){
myArray[i].quantity = myArray[i].quantity +1;
}
}
db.collection.update({"_id": doc._id},{$set: {"array":myArray}});
});
答案 1 :(得分:0)