balexandre
balexandre

Reputation: 75073

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.

Upvotes: 5

Views: 15146

Answers (2)

GreatBittern
GreatBittern

Reputation: 218

As per version 1.4 the C# driver supports LINQ. I think something like this might help:

using MongoDB.Driver.Linq;

return collectionLog.AsQueryable().Where(l => l.status == "pending").AsQueryable().OrderByDescending(l => l.date);

Please note the first AsQueryable(), that is your neccessary start to LINQ into a Mongo collection. The second AsQueryable() is neccessary because Where return IEnumerable, but OrderByDescending() takes IQueryable.

Upvotes: 2

Andre de Frere
Andre de Frere

Reputation: 2743

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);

Upvotes: 8

Related Questions