title: How to update a value and increment another in single-query using mongodb
body: <p>Is there a way to achieve the following:-</p>
  
  <pre><code>MyDocument {
      String docId;
      Integer bal;
      Set&lt;String&gt; actions;
  }
  </code></pre>
  
  <ol>
  <li><p>I need to update the field actions with some value of a user action, say from </p>
  
  <pre><code>[a1, a2]
  </code></pre>
  
  <p>to </p>
  
  <pre><code>[a1, a2, a3]
  </code></pre></li>
  <li><p>At the same time, this added action can increment the <code>bal</code> by some value so I need to ensure that <a href="https://docs.mongodb.com/manual/reference/operator/update/inc/" rel="nofollow noreferrer"><strong><code>$inc</code></strong></a> operation is also implemented for the <code>bal</code> field.</p></li>
  </ol>
  
  <hr>
  
  <p><strong>One way</strong> of achieving this I could think of was incrementing the <code>bal</code> using one update query :</p>
  
  <pre><code>Bson searchFilter = Filters.in("docId", &lt;someId&gt;);
  
  // couldn't find a cleaner way of increment in mongo-java
  BasicDBObject modifiedObject = new BasicDBObject();
  modifiedObject.put("$inc", new BasicDBObject().append("bal",2)); // any value to increment
  
  mongoCollection.updateOne(searchFilter, modifiedObject);
  </code></pre>
  
  <p>I can thereafter execute another update document query for set of <code>actions</code> update.</p>
  
  <hr>
  
  <p><strong>Another way</strong> could possibly have been updating the documents with both the fields. For which :</p>
  
  <ul>
  <li>I would have to <strong><code>find</code></strong> the document first, read the current <code>bal</code>, perform the compute at application.</li>
  <li>Then <strong><code>update</code></strong> the document with both the computed fields.</li>
  </ul>
  
  <hr>
  
  <p>In both the above approaches, I couldn't see a way of avoiding to query the DB twice. Is there any other workaround possible to achieve this currently?  </p>
  
  <p>Also, I am concerned about the atomicity with the above combination of <em><code>[UPDATE + UPDATE]</code></em> or <em><code>[GET + UPDATE]</code></em>, given multiple such concurrent queries can occur, is the concern justified even?</p>
  
  <p>Do let me know any further detail required.</p>