Getting the first document of a cursor in MongoDb + C#

感情迁移 提交于 2020-01-06 15:17:43

问题


The whole problem is like so:

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

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?

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?


回答1:


using System.Linq;

...

var whatYouAreAfter = cursor.Single();


来源:https://stackoverflow.com/questions/19487943/getting-the-first-document-of-a-cursor-in-mongodb-c-sharp

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