How to increment integer field in atomic manner? Can FindAndModify method helps?
For example document contains field count
and I wanna to increment it without retrieving full document and saving back.
I did leave a comment but I found it. The $inc
modifier will increment a field internally. Completely atomically for this exact purpose.
See here "Monog DB Atomic Operations"
Based on the answer from Paystey here's some code using version 2.1.0 of the C# driver, just in case someone else needs it:
var filter = Builders<BsonDocument>.Filter.Eq("_id", id);
var update = new BsonDocument("$inc", new BsonDocument { { "votes", 1 } });
var coll = db.GetCollection<BsonDocument>("collection");
var doc = coll.FindOneAndUpdateAsync(filter, update).Result;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.