Updating same record in mongodb transaction by two different request

I’m making a new project in Node.js where I want to update balance of an item through mongodb transaction where if the transaction fails the balance will also revert back to original value. When two concurrent request fetch the same record at the same time for update, the request which finishes first gets to update the record and the other request throws write conflict. Is there any way to handle this type of situation?

Hello @ayush_srivastav ,

Welcome to The MongoDB Community Forums! :wave:

I notice that you haven’t had a response to this topic yet, were you able to find an explanation or solution?
If not, could you please share more details regarding your use-case, are you trying to do concurrent write operations to the database?

The locks in MongoDB are acquired at the transaction level. However only write operations will lock the associated document. Read operations will not lock them. Hence the locks will be released only when the transaction is completed. Please refer Concurrency for more details.

The first part is correct however, the second transaction waiting to update the record will get the access once the lock is released to update the same record.

Can you share some sample documents and code snippet through which you are trying to achieve this? I can try reproducing the same at my end.


This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.