Consider the following document:
{
"countries" : [
{
"country" : "France",
"cities" : [
{
"city" : "Paris",
"population" : 100
}
]
},
{
"country" : "England",
"cities" : [
{
"city" : "London",
"population" : 100
},
{
"city" : "Liverpool",
"population" : 100
}
]
}
]
}
I'd like to add or update cities (imagine we have the method upsert(country, city, population)
We have 3 cases:
- Country and city already exist - This is only an update (replacing the city object)
- Country exists but city doesn't - Need only to
$push
probably - Country and city doesn't exist - Need to prepare and
$push
the country object with acities
array of size1
that contains the new city.
Is it possible to combine all these three operations in one query?
By the way,
I learned about $addToSet
but for my understanding, it compares all the object's keys and it seems to me that it's not going to work since I also have cities
which is an array.
Just updating is kinda easy with ArrayFilters:
q = {"_id":"1"}
update = {
"$set": {
"countries.$[i].cities.$[j].population": 200,
}
}
options = {
"arrayFilters": [
{
"i.country": "France"
},
{
"j.city": "Paris",
},
],
}
db.collection.updateOne(q, update, options)
ArrayFilters
countries
is collection name or key name inside document?