MongoDB atomic update on document

Hi Team

I want to know how to update the document atomically. My Scenario is, I have a spring application (with 2 instances) polling from mongodb and update the documents. In some situations 2 instances are picking the same document and overwrite the other instance update. I have to prevent this overwrite operation.

When I google the solution, I saw findAndModify is doing atomic update. I just want to understand how findAndModify works when 2 instances are trying to update the same document at the same time. Please suggest me if there are any better solution.

Prabaharan Kathiresan

Hi @Prabaharan_Kathiresa,

See my answer here

If you still have questions let me know


@Pavel_Duchovny what will happen when service1 & service2 fired up the findAndModify at the same time?

Will below process happen?

  • service1 acquires the lock on the document
  • service2 waits for the lock
  • service1 updates and releases the lock
  • service 2 acquires the lock.
  • service2 is able to view the document updated by service1

does this happen? or something else?


Service one acquire the lock and change the status field so service2 will wait and eventually will not get this specific document as its status has changed. So this read and update is atomic.

Please let me know if you have any additional questions.

Best regards,

1 Like

@Pavel_Duchovny ,
I have another usecase, but wanted to know till when does service2 wait before giving exception if service one has not released the lock?


I presume the write timeout that you specify…