mongodb
write and update opertaions are atomic, as stated in their docs.
But does it also atomic when using query?
For example:
db.collection.update( { id : 1 , count : 0 } , { $inc : { count : 1 } } )
If I execute this operation in a multi threaded environment, is it possible that at some point the value of count
in the document with id
equal to 1 will be greater than 1?
Any modification to a single document is atomic.
Using your example, let's say there are two threads trying to update that document using the same query:
Thread A: db.collection.update({_id: 1, count: 0}, {$inc: {count: 1}})
Thread B: db.collection.update({_id: 1, count: 0}, {$inc: {count: 1}})
with the collection containing the document:
collection: {_id: 1, count: 0}
If thread A
managed to update the document before thread B
, the collection would then contain:
collection: {_id: 1, count: 1}
Thread B
will search for a document matching _id:1, count:0
but since that document was already modified by thread A
, the update in thread B
will not proceed (since the document no longer "exists" as thread B
is concerned).
In other words, thread A
will return nMatched: 1, nModified: 1
, and thread B
will return nMatched: 0, nModified: 0
.
To specifically answer your question, there will not be a case where a document {_id: 1, count: 2}
will exist.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With