Reputation: 21
I have a mongodb collection that looks something like the following:
_id: ObjectId("123456789")
continent_name: "Europe"
continent_id: "001"
countries: Array
0
country_name: "France"
country_id: "011"
cities: Array
0
city_name: "Paris"
city_id: "101"
1
city_name: "Maseille"
city_id: "102"
1
country_name: "England"
country_id: "012"
cities: Array
0
city_name: "London"
city_id: "201"
1
city_name: "Bath"
city_id: "202"
And so on for other continents>countries>cities. I'm unclear on what approach to take when updating this collection.
Let's say I run my data collection again and discover a new city in England, resulting in an array for [London, Bath, Manchester], how do I update the value of Europe>England>[] pythonically without touching France?
Is it possible to search where(continent=Europe && country=England)
?
My current working theory is to do something like the following:
def mongo_add_document(continent, country, cities):
data= {
"continent_name": continent["name"],
"continent_id": continent["id"],
"countries": [
{
"country_name": country["name"],
"country_id": country["id"],
"cities": [
{"city_id": city["id"], "city_id": city["id"]} for city in cities
]
}
]
}
cities.find_one_and_update(
{"continent_id": continent["id"]},
data,
upsert=True
)
But my concern is this will overwrite other countries in the continent document.
Upvotes: 0
Views: 91
Reputation: 620
db.getCollection('cities')
.updateOne({"continent_name": "Europe", "countries.country_name": "England", "countries.cities.city_name" : {$ne: "Manchester"}},
{$push: {"countries.$.cities": {"city_name": "Manchester", "city_id":"whatever"}}})
Upvotes: 1