Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the last item in a MongoDB collection?

I'm using MongoDB for sometime to perform all sort of fast inserts or having as a log, but I'm having some trouble to get a really simple query

How, in Mongo, would I do to get a similiar to this T-SQL

SELECT TOP 1 [date] FROM [Collection] ORDER BY [date] desc

In other words, what is the last date in the collection.

I'm trying to use FindOne or any other that can return one document, but none accepts a sortBy property... how would I do this?

var query = Query.EQ("status", "pending");
var sortBy = SortBy.Descending("date");

return collectionLog.FindOneAs<BsonDocument>(query, sortBy);

The last line above would be perfect, but this method only accepts the query parameter.

like image 371
balexandre Avatar asked Sep 08 '12 17:09

balexandre


1 Answers

There is no .SetSortOrder() method of FindOneAs in the C# driver. This is because FindOneAs returns a document while .SetSortOrder() is a member of MongoCursor.

The equivalent query would be something similar to:

var query = Query.EQ("status", "pending");
var sortBy = SortBy.Descending("date");

return collectionLog.FindAs<BsonDocument>(query).SetSortOrder(sortby).SetLimit(1);
like image 53
Andre de Frere Avatar answered Sep 24 '22 02:09

Andre de Frere