Igor
Igor

Reputation: 1434

MongoDB findAndModify: >>> find and update object in document's array

Question :

I try to look after object in document's array and update it.

Syntax bellow give me object i want, but i don't know how to update this object. I tried to use this statement in findAndModify but it seems that i cannot use $elemMatch in findAndModify method

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

Sample JSON i try to change

[{
"_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"}]
 }]

Summary:

I have to find document in collection and then in document's array find object and update this object.

So my logic looks like this

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

Upvotes: 0

Views: 910

Answers (1)

vladzam
vladzam

Reputation: 5918

You can run the following query in order to achieve what you are looking for:

//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'}}
});

This query will update the second document:

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

You can read more about updating documents using the $ positional operator here

Upvotes: 2

Related Questions