MongoDB findAndModify:>>>查找并更新文档数组中的对象

时间:2015-03-12 16:50:05

标签: javascript arrays mongodb express

问题:

我尝试在文档的数组中查找对象并更新它。

语法bellow给我我想要的对象,但我不知道如何更新这个对象。我试图在findAndModify中使用这个语句,但似乎我不能在findAndModify方法中使用$ elemMatch

  db.users.find({"username":"username"},{"array":{$elemMatch:{"name":"name"}}})

示例JSON我尝试更改

[{
"_id": ObjectId("5501b8fb77382c23704543fd"),
"username": "ker",
"password": "ker",
"character": "pet",
"visits": [],
"pets": [{"name": "Jura", "kind": "dog", "age": "2"}, {"name": "Ala",  "kind": "dog", "age": "5"}]
}, {
"_id": ObjectId("5501b8fb77382c23704543fd"),
"username": "mer",
"password": "mer",
"character": "pet",
"visits": [],
"pets": [{"name": "Ita", "kind": "cat", "age": "6"}, {"name": "Esa", "kind": "cat", "age": "1"}]
 }]

要点:

我必须在集合中找到文档,然后在文档的数组中查找对象并更新此对象。

所以我的逻辑看起来像这样

 db.collection.findAndModify({query:{Find Document In Collection THEN in document's array(pets) find object}, update:{$set:{New Values For Object}}})

1 个答案:

答案 0 :(得分:2)

您可以运行以下查询以实现您的目标:

//findAndModify will always refer to one document
db.collection.findAndModify({

    //Find the desired document based on specified criteria
    query: { username: 'mer', pets: { $elemMatch: { name: 'Esa'}}},

    //Update only the elements of the array where the specified criteria matches
    update: { $set: { 'pets.$.name': 'CHANGED'}}
});

此查询将更新第二个文档:

{
        "username" : "mer",
        "password" : "mer",
        "character" : "pet",
        "visits" : [ ],
        "pets" : [
                {
                        "name" : "Ita",
                        "kind" : "cat",
                        "age" : "6"
                },
                {
                        "name" : "CHANGED",
                        "kind" : "cat",
                        "age" : "1"
                }
        ]
}

您可以使用$位置操作符here

了解有关更新文档的详情