Thomas Thomas - 5 months ago 81
C# Question

Find and Modify with MongoDB C#

I am trying to replace the following code:

var R = Challenges.FindAll().SetSortOrder("UseCount").First();
var Q = Query.EQ("_id", R._id);
var U = Update.Inc("UseCount", 1);
Challenges.Update(Q, U);
return R;

Here's the intent:

I have a field in a DB called 'UseCount' and I want to find the record with the lower value. If many records have the same value, I just want the first (it's not important).

I want, at the same time, to increment the 'UseCount' field by one.

I have seen examples of FindAndModify, but it seems geared at comparisons with fields (ie: "field" = value) , not a search like I am doing.

What would be the best / most efficient way to handle this?


Following code does it (C# MongoDB.Driver 2.0)

var collection = database.GetCollection<BsonDocument>("product");
var filter = new BsonDocument();
var update = Builders<BsonDocument>.Update.Inc("UseCount", 1);
var sort = new FindOneAndUpdateOptions<BsonDocument>
            Sort = Builders<BsonDocument>.Sort.Ascending("UseCount")
await collection.FindOneAndUpdateAsync(filter, update, sort);