我这样设置查询以允许分页。虽然这有效,但我基本上必须运行相同的查询两次以获得查询的总匹配结果并允许分页。有什么办法可以将其组合成一个查询吗?
public SearchResult GetResults()
{
//query is built elsewhere
var totalResults = (from i in Collection.Find(query)
select i).Count();
var results = (from i in Collection.Find(query)
select i)
.Skip(recordsToSkip)
.Take(recordsToTake)
.ToList();
//SearchResult is defined elsewhere
return new SearchResult
{
Results = results,
TotalResults = totalResults
};
}
最佳答案
首先,要获得计数,您不应该执行 linq 查询然后计算结果。这种方式是枚举所有的结果,然后统计出来,开销很大。您应该改用:
var totalResults = Collection.Find(query).Count()
此 Count
方法是在 MongoCursor
本身上定义的,并将在 mongo 中而不是在您的 .Net 应用程序中计算结果。
我想这才是问题背后的真正问题。但是如果你仍然想合并这两个查询,你可以这样做:
var results = (from i in Collection.Find(query) select i).ToList();
var totalResults = results.Count();
var page = results
.Skip(recordsToSkip)
.Take(recordsToTake)
.ToList();
这将获取整个集合,对其进行计数,并返回其中的一页。不过,我不建议您这样做,因为您不需要整个集合。
P.S:当您对 Find 的结果使用 Linq 时,它会在您的应用程序中而不是在数据库中进行过滤,因此您应该将查询更改为这个查询:
var results = Collection.Find(query)
.SetSkip(recordsToSkip)
.SetLimit(recordsToTake)
.ToList();
关于c# - 获取总结果数并允许在与 MongoDB 的同一查询中进行分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21000247/