Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is mongodb update with query atomic?

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?

like image 301
itaied Avatar asked Jul 16 '18 16:07

itaied


1 Answers

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.

like image 56
kevinadi Avatar answered Nov 20 '22 06:11

kevinadi