使用MongoDB C#查找和修改 [英] Find and Modify with MongoDB C#

查看:389
本文介绍了使用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;

这是目的:
我在数据库中有一个名为"UseCount"的字段,我想找到值较低的记录.如果许多记录具有相同的值,那么我只想要第一个(不重要).
我想同时将'UseCount'字段加1.

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.

我已经看到了 FindAndModify 的示例,但它似乎是针对与字段(即"field" = value)进行比较,而不是像我正在做的那样进行搜索.

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?

推荐答案

以下代码做到了(C#MongoDB.Driver 2.0)

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

这篇关于使用MongoDB C#查找和修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆