简体   繁体   中英

Updating nested documents in mongodb using pymongo

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.

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"}}})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM