How does MongoDB deal with concurrent updates?

Solution 1:

MongoDB used a process wide write lock to guarantee that only one write operation (update/insert/remove) can be performed at a time. As such it automatically solves concurrency issues since write concurrency simply isn't allowed.

If 4 threads attempt an update operation one of them will take the write lock, do its update and release the lock. After that one of the remaining 3 will grab the lock, do its update, etc.

Concurrency only comes into play if your operation cannot be wrapped in a single write operation. Note that for the most common usecase (find a doc, update it and grab the new version atomically) MongoDB offers the "findAndModify" command which does just that : http://www.mongodb.org/display/DOCS/findAndModify+Command

UPDATE : Locking is more granular these days.

Solution 2:

Use modifier operations:

$inc $set $unset $push $pushAll $addToSet $pop $pull $pullAll $rename $bit

all of them are atomic.