[嗨,我在我的dotnet核心应用程序中使用最新的MongoDB C#驱动程序版本2.10。我有50+百万条记录。所有列均已正确索引,在Compass上的查询工作正常。
这是我的方法。
/// <summary>
/// fetch all items in collection with paging and ordering in direction
/// </summary>
/// <param name="pageIndex">page index, based on 0</param>
/// <param name="size">number of items in page</param>
/// <param name="order">ordering parameters</param>
/// <param name="fields">required fields</param>
/// <param name="filters">search criteria</param>
/// <returns>collection of entity</returns>
Task<(IEnumerable<T> result, long count)> FindAllListAsync(int? pageIndex, int? size, string order = null, string fields = null, string filters = null);
这里是实现
public IEnumerable<T> FindAll(int? pageIndex, int? size, out long count, string order = null, string fields = null, string filters = null)
{
IFindFluent<MongoDB.Bson.BsonDocument, MongoDB.Bson.BsonDocument> fluent;
long totalCount;
if (!string.IsNullOrEmpty(filters))
{
fluent = CollectionAsBson.Find(filters);
totalCount = fluent.CountDocuments();
}
else
{
fluent = CollectionAsBson.Find(FilterDefinition<MongoDB.Bson.BsonDocument>.Empty);
totalCount = Collection.EstimatedDocumentCount();
}
if (pageIndex.HasValue && size.HasValue)
fluent = fluent.Skip((pageIndex - 1) * size);
if (size.HasValue)
fluent = fluent.Limit(size);
if (!string.IsNullOrEmpty(order))
{
fluent = fluent.Sort(order);
}
fluent.Options.Collation = new Collation("en");
IEnumerable<T> result = fluent.Project<T>(fields).ToList();
count = totalCount;
return result;
}
我这样叫
public async Task<(IEnumerable<T> result, long count)> FindAllListAsync(int? pageIndex, int? size, string order = null, string fields = null, string filters = null)
{
long localCount = 0;
var list = await Task.Run(() => FindAll(pageIndex, size, out localCount, order, fields, filters)).ConfigureAwait(true);
return (list, localCount);
}
此代码需要太多时间才能通过分页获得5条记录。当我返回fluent.Project(fields).ToEnumerable()时,它的返回值带有未评估的异步游标。但是,当我放置诸如AutoMapper之类的映射代码甚至之后执行toList()时,这会花费太多时间。甚至countDocuments也花费太多时间。
这是我的索引。
需要帮助
您是否尝试过AsQueryable()?并转换您的查询所需的数据。