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

只谈情不闲聊 提交于 2020-01-14 09:47:08

问题


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.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/12332819/how-do-i-get-the-last-item-in-a-mongodb-collection

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