在MongoDb + C#中获取光标的第一个文档 [英] Getting the first document of a cursor in MongoDb + C#

查看:59
本文介绍了在MongoDb + C#中获取光标的第一个文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

整个问题是这样的:

在MongoDb中具有文档集合,找到第一个 根据查询和订单.

Having a collection of documents in MongoDb, find the first one according to a query and an order.

由于MongoDb中的 FindOne 不接受一个订单,这样做的方法是返回CursorLimit为1.可以在C#中完成,例如:

Since FindOne in MongoDb does not accept an order, the way to do so is to return a Cursor with a Limit of one. It is done in C# like so:

var query = Query<Doc>.EQ(e => e.Deleted, false);
var sortBy = SortBy<Doc>.Ascending(e => e.Date);
var cur = colletion.FindAs<Doc>(query).SetSortOrder(sortBy).SetLimit(1);

然后,我需要以某种方式将找到的文档从光标中取出!但是如何?

Then, somehow, I need to take the found document out of the cursor! But how?

光标带有Count()方法,该方法返回找到的文档数,但没有返回文档的方法!我发现的唯一方法是使用可笑的迭代!!

The cursor comes with a Count() method which returns the number of found documents but it has no means to return the document!? The only way I found is using iteration which is ridiculous!!

foreach (var doc in cur)
{
    return doc;
}
return null;

有人知道更好的方法吗?

Does anyone know of a better way?

推荐答案

using System.Linq;

...

var whatYouAreAfter = cursor.Single();

这篇关于在MongoDb + C#中获取光标的第一个文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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