Question :
I am attempting to locate an object within a document's array and make updates to it.
The syntax below provides me with the desired object, but I am unsure of how to update it. I attempted to use this query in findAndModify, but it seems that $elemMatch cannot be used in the findAndModify method.
db.users.find({"username":"username"},{"array":{$elemMatch:{"name":"name"}}})
Example JSON I am trying to modify
[{
"_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"}]
}]
Overview:
My goal is to locate a specific document within a collection, then pinpoint an object within the document's pets array and make updates to that object.
Therefore, my logic follows this pattern
db.collection.findAndModify({query:{Find Document In Collection THEN in document's array(pets) find object}, update:{$set:{New Values For Object}}})