'MongoDB - Update an object from a nested array
{ _id: 1, first : "Maria",
travel : [
{ country: "Canada", visits: 3, rating: 7 },
{ country: "Poland", visits: 1, rating: 8 },
{ country: "Thailand", visits: 2, rating: 9 } ] },
{ _id: 2, first : "Chen",
travel : [
{ country: "Thailand", visits: 3, rating: 7 },
{ country: "Canada", visits: 2, rating: 9 },
{ country: "Costa Rica", visits: 4, rating: 8 } ] },
{ _id: 3, first : "Gladys",
travel : [
{ country: "Canada", visits: 1, rating: 8 },
{ country: "Thailand", visits: 2, rating: 9 },
{ country: "Australia", visits: 3, rating: 10 } ]}
])
I need to update the visits Maria made to Canada to 5, so I have to use some sort of "double filter" (?) But I'm not sure how to do that
Solution 1:[1]
Okay, I got how to make that "double filter" : Array filters and $[identifier] Here
db.viajeros.updateOne( { first: "Maria"},
{ $set: {"travel.$[elem].visits": 5}},
{ arrayFilters: [{"elem.country": "Canada"}]} )
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Grefuwan |
