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.

Thanks
Prabaharan Kathiresan

Hi @Prabaharan_Kathiresa,

See my answer here

If you still have questions let me know

Pavle

@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?

@Divine_Cutler,

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,
Pavel

1 Like