The data in this post is a hypothetical similar to a problem I’m dealing with.
I am working with Python using pymongo.
I have a document that looks something like this:
_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"
I’ve run my data collection and received an array for cities in england, including cities already in the document, e.g. London, Bath, Manchester, Liverpool.
Given the nature of the data I am collecting, when I (infrequently) run my data collection, I want to either create a new country with its own cities aray, or replace the entire existing cities array with a new one, but have no idea how to go about it.
I received a suggestion that looks something like this:
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"}}})
However this results in duplicate cities.
As I said, I need to replace the entire nested array if it already exists, or create a new continent/country object if it doesn’t.
I THINK what I need to do is something like the following:
....updateOne(
{"continent_name": "Europe", "countries_name": "England"},
{$set: {"countries.cities.$[]": [ARRAY OF CITIES]},
upsert: True
)
However I can’t figure out the correct dot notation in the $set section, receiving errors with everything I’ve tried.
Anyone know a potential solution?
Goals:
If the continent.country already exists, replace the cities array.
If the continent exists but not the country, create the country with a new cities array.
If the continent doesn’t exist already, create a new document entirely.