我正在尝试使用 MongoDB 的 C# 驱动程序从 MongoDB 中的“交易”集合中检索五个最近的文档。我可以用下面的代码来完成。
public IList<TEntity> GetRecentFive()
{
IList<TEntity> entities = new List<TEntity>();
using (MongoDbContext dbContext = new MongoDbContext(_dbFactory))
{
var cursor = dbContext.Set<TEntity>().FindAll().SetSortOrder(SortBy.Descending("ModifiedDateTime")).SetLimit(5);
foreach (TEntity entity in cursor)
{
entities.Add(entity);
}
}
return entities;
}
但我只想获取最近的 5 个文档,FindAll() 会加载集合中的所有文档。我试着用 Find() 来做,但它需要一个查询作为参数。如何在 Mongo 驱动程序中为 C# 编写“orderby”查询以进行排序?
https://stackoverflow.com/a/2148479/778101在这里问了一个类似的问题。但是接受的答案对我不起作用。
最佳答案
using (MongoDbContext dbContext = new MongoDbContext(_dbFactory))
{
var query = new QueryDocument();
var cursor =
dbContext.Set<TEntity>().Find(query).SetSortOrder(SortBy.Descending("ModifiedDateTime")).SetLimit(5);
foreach (TEntity entity in cursor)
{
entities.Add(entity);
}
}
也是解决这个问题的正确方法
关于c# - 如何在 Mongo 驱动程序中为 "orderby"编写查询以供 C# 排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9325418/