本文介绍了在MongoDb + C#中获取光标的第一个文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
整个问题是这样的:
由于MongoDb中的 FindOne
不接受一个订单,这样做的方法是返回Cursor
且Limit
为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#中获取光标的第一个文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!