Senthil Umakandan
Senthil Umakandan

Reputation: 93

How can we achieve "Select For Update" in 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" }

Upvotes: 9

Views: 7822

Answers (1)

Barış Uşaklı
Barış Uşaklı

Reputation: 13532

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 }
});

Upvotes: 6

Related Questions