title: MongoDB - Merge Update
body: <p>I am having a little problem updating a MongoDB document (using pymongo). I have found several answers for similar questions that didn't work out for me.</p>
  
  <p>Background: I am crawling some websites and saving information to a MongoDB.</p>
  
  <p>Assume I got the following document from a web page and stored in a MongoDB collection:</p>
  
  <pre><code>original_doc = {
      'id': some_id,
      'data': {
          'key1': value1,
          'key2': value2
      }
  }
  </code></pre>
  
  <p>After some time, I may want to crawl the same page again and get the following document:</p>
  
  <pre><code>new_doc = {
      'id': some_id,
      'data': {
          'key2': new_value2,
          'new_key3': new_value3
      }
  }
  </code></pre>
  
  <p>Now I want to update the already existing MongoDB document in the collection so it looks like this:</p>
  
  <pre><code>updated_doc = {
      'id': some_id,
      'data': {
          'key1': value1,
          'key2': new_value2,
          'new_key3': new_value3
      }
  }
  </code></pre>
  
  <p>So basically the old document should be overwritten with the new document, but without erasing / losing data from the original document, that does not exist in the new document.</p>
  
  <p>I first thought I could use the $set to update the document, but then the (key1, value1) entry gets lost. And I do not know the key of the new entry as I am not in control of the data returned by the website, so I can't just use {$set: {data.new_key3: new_doc}} either.</p>
  
  <p>Is there a solution for this?</p>