title: MongoDB Transactions: WriteConflict Error
body: <p><strong>Environment</strong>:</p>
  <ul>
  <li>MongoDB:  (Atlas 4+)</li>
  <li>Driver: 4.2.3</li>
  <li>We are using Spring Boot Data MongoDB (2.5.4)</li>
  </ul>
  <p>We are using MongoDB Transactions using the callback API. Same happens with Core API as well.</p>
  <p><strong>Sample</strong>:</p>
  <pre><code>    private ThreadLocal&lt;MongoOperations&gt; sessionMongoTemplate;
  
      try (final ClientSession session = getClientSession()) {
         this.sessionMongoTemplate = ThreadLocal.withInitial(() -&gt; getMongoOperations().withSession(session));
  
         session.withTransaction(() -&gt; {
             // do some work
             // call a method which does (sessionMongoTemplate.get().insert(entity);) 
             // (this throws WriteConflict Error)
         });
     } 
  </code></pre>
  <p><strong>Error</strong>:</p>
  <p><em>com.mongodb.MongoCommandException: Command failed with error 112 (WriteConflict): 'WriteConflict error: this operation conflicted with another operation. Please retry your operation or multi-document transaction.' on server abc.mongodb.net:1234. The full response is
  {
  &quot;errorLabels&quot;: [
  &quot;TransientTransactionError&quot;
  ],
  &quot;ok&quot;: 0,
  &quot;errmsg&quot;: &quot;WriteConflict error: this operation conflicted with another operation. Please retry your operation or multi-document transaction.&quot;,
  &quot;code&quot;: 112,
  &quot;codeName&quot;: &quot;WriteConflict&quot;</em></p>
  <p><strong>Query:</strong><br />
  We associated MongoOperations/Template with ClientSession already.
  That session opened a transaction.
  However, when code uses the SessionScoped MongoOperations, it fails as if it has no knowledge of opened transaction.</p>
  <p>Can we not use this approach?</p>
  <blockquote>
  <p>As per the example in :
  <a href="https://docs.mongodb.com/v4.2/core/transactions-in-applications/" rel="nofollow noreferrer">https://docs.mongodb.com/v4.2/core/transactions-in-applications/</a>
  within transaction body, we used MongoClient and it works fine. Can we
  not use SessionScoped MongoTemplate?</p>
  </blockquote>