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