From the MongoDB Update documentation they talk about the update operators being atomic. If the below query is called five times at the same instant and Zugwalt’s reputation starts at zero, I’d expect at the end for the reputation to be 5:
db.rep.update({_id: "Zugwalt"}, {$inc: {reputation: 1}});
However what if the update query is this?
db.rep.update({_id: "Zugwalt", reputation: {$lte: 3}}, {$inc: {reputation: 1}});
Would the reputation always only be updated three times or is there some weird race conditions where it could be more?
My particular case is using an active user to “claim a document”. I execute a query similar to:
db.myCollection.update({_id: "doc_id", activeUser: {$exists: false}}, {$set: {activeUser: "Zugwalt"}});
Ideally if this query fires multiple times at the same instance only one update will result in the collection being modified. However If the search component isn’t atomic with the update I could see a race condition where its first updated to set the activeUser to one user, and then immediately to another.
Side note: it seems more clear that the findAndModify command has this kind of atomicness, however I don’t want to use it as in our empirical testing with our node-js driver it seems much slower overall under heavy load.
In MongoDB updates are atomic. If you don’t need to get the document back, you don’t need to use findAndModify.
In the scenarios you give, the expected thing will happen – in the first case reputation will end up as 5, in the second it’ll be 4.
In your case only one update will successfully set activeUser.
Here is a link that discusses atomic operations in MongoDB.