Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we achieve "Select For Update" in Mongodb?

Tags:

mongodb

Below is my sample document. I wanted to load this document & read total_comments value & perform certain logic on it and update the document again with new total_comments value. How should I ensure total_comments value is not updated by some other request before I complete my above explained steps?

{ "_id" : ObjectId("56782a933d5c6ca02100002b"), "total_comments" : 12, "time_updated" : 1450715963 }

In mysql, we can do it by doing "select for update"?. How can we achieve this in Mongodb?.

Here is my MongoDB version:

> db.version()
3.0.7

Here is my storage engine details:

> db.serverStatus().storageEngine
{ "name" : "mmapv1" }
like image 804
Senthil Umakandan Avatar asked Dec 22 '15 17:12

Senthil Umakandan


Video Answer


1 Answers

Use findAndModify() to update a document.

For example you can increment total_comments by 1 with

db.collection.findAndModify({
  _id: ObjectId("56782a933d5c6ca02100002b")
}, {}, {
  $inc: { "total_comments": 1 }
});
like image 92
Barış Uşaklı Avatar answered Oct 19 '22 21:10

Barış Uşaklı