This cannot be done with a single query. Here is how I would do it:
- Have a field on the document called
locked
. Run afindAndModify
to grab the document if thelocked
field is false, and set the locked field to theDate()
that it is locked at. This will stop other application instances from modifying the document, providing they also check for thelocked
field. - Modify the document application side, then atomically update it, setting
locked
to false. As long as anything modifying the document runs afindAndModify
on thelocked
field, this entire modification should be atomic.
Make sure to have a threshold at which a lock times out, so that documents do not become locked indefinitely if a machine blows up. This means that when updating the document the second time (and releasing the lock), the application should make sure that the date in the document is what it expects, to make sure it still has the lock.