Strongly Consistent Read

Hi everyone, assuming we have a collection that handles the booking of an hotel room.
In particular there is only one room remaining and 2 different clients perform concurrently the following query:

db.rooms.updateOne({numRoom: {$gt : 0}}, {$inc: {numRoom: -1}})

The expected behavior is that only one client performs the updateOne operation. Is there a way to enforce this behavior?

I mean, only one client update the document by performing the $inc operation, while the other one does not update any document

Only one will find and update the document with numRoom:{$gt:0}.

The other will get matchedCount:0 as the result of the operation.

So MongoDB always guarantees strongly consistent reads?

If so, I could also build a collection that acts as a centralized Mutex.
Each document represents a resource and the locking operation on that resource consists of:

(1) If the resource does not exist, I create the document (with an upsert operation)

(2) If the resource exists, upsert is not performed and the client is locked out.

If mongoDB guarantees strongly consistent reads, even if 100 requests arrive at the same time, only one will be able to block the resource by upserting, and the remaining 99 will have upsertedCount = 0. Is that so?

MongoDB has what it takes to do what you want.

It depends. See

1 Like