How to ensure multiple findOneAndUpdate does not return the same document

Consider the following collection

[
{_id: 0, status: 'pending'},
{_id: 1, status: 'pending'}
]

If I run the following operation twice concurrently I would expect to get both documents set to processing and returned

findOneAndUpdate({ status: 'pending' }, { $set: { status: 'processing' } })

However what I experience is that the first document is updated and returned twice. Am I misunderstanding something?

1 Like

Hello @Andreas_Hald ,

Welcome to The MongoDB Community Forums! :wave:

I added the mentioned documents and ran the same query twice below is the response I got

db.collectionA.findOneAndUpdate({ status: 'pending' }, { $set: { status: 'processing' } })
{
  _id: 0,
  status: 'pending'
}
db.collectionA.findOneAndUpdate({ status: 'pending' }, { $set: { status: 'processing' } })
{
  _id: 1,
  status: 'pending'
}

So, it is working as expected, if the two queries run one after another.

By concurrently , do you mean you’re trying to run/update the same document with two queries at the same time? Could you post an example code that can reproduce what you’re seeing?

Regards,
Tarun

1 Like

FindandUpdate should be atomic operation. Maybe explain a bit on how you run your tests.

1 Like