Find and Modify with MongoDB C#

社会主义新天地 提交于 2020-02-04 00:41:08

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/30540994/find-and-modify-with-mongodb-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!