title: MongoDb updateMany() with different $set objects
body: <p>I am working on a migration function that needs to retrieve soccer game results in certain time intervals and update existing bet documents for those games in MongoDB.This code will be called multiple times throughout the day and I'm looking for an optimized solution regarding the computation performance</p>
  
  <p>The data structure looks like this.</p>
  
  <pre><code>{
      "games": {
          "2324754": {
              "id": "2324754",
              "comp_id": "1005",
              "formatted_date": "14.03.2018",
              "localteam_name": "Barcelona",
              "localteam_score": "3",
              "visitorteam_name": "Chelsea",
              "visitorteam_score": "0"
          },
          "2324756": {
              "id": "2324756",
              "comp_id": "1005",
              "formatted_date": "14.03.2018",
              "localteam_name": "Beşiktaş",
              "localteam_score": "1",
              "visitorteam_name": "Bayern München",
              "visitorteam_score": "3",
          }
      },
      "bets": [
          {
              "_id": "5aa9535c6c4f437de713452a",
              "match_id": "2324756"
          },
          {
              "_id": "5aacf9605c41bc0b3db304fd",
              "match_id": "2324754"
          }
      ]
  }
  </code></pre>
  
  <p>One option is iterating the bets array and calling <code>findOneAndUpdate()</code> on individual bet documents.Due to performance issues that would not work very well for bets array with a count of 150-200 elements.</p>
  
  <p>The question is would it be possible to achieve this migration with <code>updateMany()</code> operation.
  It would not be a problem to query all documents with the given <code>match_id</code> but how would one build a set condition for <code>updateMany()</code>?</p>
  
  <p>Given examples in the documentation assumes that desired fields of multiple documents are updated with same values.
  <a href="https://docs.mongodb.com/manual/reference/method/db.collection.updateMany/" rel="nofollow noreferrer">https://docs.mongodb.com/manual/reference/method/db.collection.updateMany/</a></p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>Another option is creating a Bulk operation and doing <code>findOneAnUpdate()</code> inside the for loop.But once again I'm not sure if that would be performant enough. Can anyone confirm that this would be the best/only option for his?At least that would not load the mongo server with multiple update requests.</p>
  
  <p><a href="https://docs.mongodb.com/manual/reference/method/Bulk.find.update/" rel="nofollow noreferrer">https://docs.mongodb.com/manual/reference/method/Bulk.find.update/</a></p>
  
  <pre><code>var bulk = db.items.initializeUnorderedBulkOp();
  //Iterate Bets
  //findOneAnUpdate
  bulk.execute();
  </code></pre>