1

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.

Edward83
  • 6,664
  • 14
  • 74
  • 102

2 Answers2

2

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"

Paystey
  • 3,287
  • 2
  • 18
  • 32
  • ahh you wanted specific driver help, you should be able to use it like any other modifier. See the link I just added, you just pass the fields to `$inc` that you want incrementing. That;s a fairly standard feature and shouldn't be too different in your driver. If you post some code on your question we'll probably be able to figure it out. – Paystey Apr 24 '12 at 12:33
  • Paystey, thank you, I found example of using Update http://www.mongodb.org/display/DOCS/CSharp+Driver+Tutorial#CSharpDriverTutorial-Updatemethod – Edward83 Apr 24 '12 at 12:36
1

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;
Paul
  • 1,224
  • 2
  • 14
  • 31