14

I am trying to update a document using two parallel multi-document transactions and I get the following error: ‍‍‍

MongoError: WriteConflict error: this operation conflicted with another operation. Please retry your operation or multi-document transaction.

How can I fix this?

Michal Miky Jankovský
  • 3,089
  • 1
  • 35
  • 36
Emad Mamaghani
  • 343
  • 2
  • 14

1 Answers1

4

WriteConflicts occur in mongodb when two or more write operations try to modify a document at the same time. Since mongodb uses optimistic concurrency control, it fails the latter operation and retries the latter write operation internally.

Transactions in mongodb can be implemented in 2 ways:

  1. Core api - the retry logic is not implemented internally but rather left for the developers to incorporate
  2. Callback api - the retry logic is already incorporated

I believe you are using the core api approach and that's why it is giving this error. Try switching to callback api approach to solve it.

Naveen Chahar
  • 561
  • 3
  • 10
  • 1
    Refer these for further clarification - https://www.mongodb.com/docs/manual/core/transactions-in-applications/ and https://blog.clairvoyantsoft.com/mongodb-transaction-management-884f82f62767 – Naveen Chahar Feb 16 '23 at 20:58