MongoDB通过它的嵌套对象数组查询文档,并更新文档数组中与查询匹配的所有对象

时间:2018-03-28 19:27:21

标签: arrays mongodb

所以我在一个集合中有以下文件。

{
       _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”的对象,并使用新值更新这些对象数量属性。

2 个答案:

答案 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)

enter image description here

<add name="{name}" providerName="System.Data.SqlClient" connectionString="Data Source={serverName};Initial Catalog={dbName};Integrated Security=SSPI;Persist Security Info=False;Pooling=False;MultipleActiveResultSets=False;Encrypt=False;TrustServerCertificate=True" />