Concurrent findAndModify on the same document

257 Views Asked by At

Say there are 2 active transactions A and B (both are active, thus not yet committed). First, A does findAndModify on a random document matching the predicate and keeps the transaction active. Now B does the same findAndModify and happens to land on the same document. What happens now? Is B blocked until A ends?

If so, is there a way to let B pick another document which also matches the given predicate, but which is not locked by a concurrent session? In SQL, this would be a SKIP LOCKED directive.

1

There are 1 best solutions below

0
On

Now B does the same findAndModify and happens to land on the same document. What happens now? Is B blocked until A ends?

When you try to commit the second transaction, you should get WriteConflict error.

As well, this is trivially testable.

If so, is there a way to let B pick another document which also matches the given predicate, but which is not locked by a concurrent session? In SQL, this would be a SKIP LOCKED directive.

Unlikely since this would require transactions to inspect the state of all other transactions. In a sharded cluster, each transaction is local to a mongos and this isn't even possible in general.

Regarding "skip locked", MVCC does not require locking, so there may well be nothing locked to be skipped.