问题
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