简体   繁体   English

如何获取MongoDB集合中的最后一项?

[英]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 我正在使用MongoDB来执行所有类型的快速插入或作为日志,但是我遇到了一些非常简单的问题

How, in Mongo, would I do to get a similiar to this T-SQL 在Mongo中,我将如何与此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? 我正在尝试使用FindOne或任何其他可以返回一个文档,但没有人接受sortBy属性...我该怎么做?

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. 上面的最后一行是完美的,但此方法只接受query参数。

There is no .SetSortOrder() method of FindOneAs in the C# driver. 没有.SetSortOrder()的方法FindOneAs在C#的驱动程序。 This is because FindOneAs returns a document while .SetSortOrder() is a member of MongoCursor . 这是因为FindOneAs返回文档,而.SetSortOrder()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);

As per version 1.4 the C# driver supports LINQ. 根据1.4版本,C#驱动程序支持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. 请注意第一个AsQueryable() ,这是LINQ进入Mongo集合的必要开始。 The second AsQueryable() is neccessary because Where return IEnumerable, but OrderByDescending() takes IQueryable. 第二个AsQueryable()是必要的,因为Where返回IEnumerable,但OrderByDescending()需要IQueryable。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM