title: Updating nested documents in mongodb using pymongo
body: <p>I have a mongodb collection that looks something like the following:</p>
  <pre><code>_id: ObjectId(&quot;123456789&quot;)
  continent_name: &quot;Europe&quot;
  continent_id: &quot;001&quot;
  countries: Array
    0
      country_name: &quot;France&quot;
      country_id: &quot;011&quot;
      cities: Array
        0
          city_name: &quot;Paris&quot;
          city_id: &quot;101&quot;
        1
          city_name: &quot;Maseille&quot;
          city_id: &quot;102&quot;
    1
      country_name: &quot;England&quot;
      country_id: &quot;012&quot;
      cities: Array
        0
          city_name: &quot;London&quot;
          city_id: &quot;201&quot;
        1
          city_name: &quot;Bath&quot;
          city_id: &quot;202&quot;
  </code></pre>
  <p>And so on for other continents&gt;countries&gt;cities.
  I'm unclear on what approach to take when updating this collection.</p>
  <p>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&gt;England&gt;[] pythonically without touching France?</p>
  <p>Is it possible to search <code>where(continent=Europe &amp;&amp; country=England)</code>?</p>
  <p>My current working theory is to do something like the following:</p>
  <pre><code>def mongo_add_document(continent, country, cities):
      data= {
          &quot;continent_name&quot;: continent[&quot;name&quot;],
          &quot;continent_id&quot;: continent[&quot;id&quot;],
          &quot;countries&quot;: [
              {
                  &quot;country_name&quot;: country[&quot;name&quot;],
                  &quot;country_id&quot;: country[&quot;id&quot;],
                  &quot;cities&quot;: [
                      {&quot;city_id&quot;: city[&quot;id&quot;], &quot;city_id&quot;: city[&quot;id&quot;]} for city in cities
                  ]
              }
          ]
      }
  
      cities.find_one_and_update(
          {&quot;continent_id&quot;: continent[&quot;id&quot;]},
          data,
          upsert=True
      )
  </code></pre>
  <p>But my concern is this will overwrite other countries in the continent document.</p>