C#MongoDB驱动程序ToList()的分页查询,具有在50M左右的大数据上减慢索引的速度

问题描述 投票:0回答:1

[嗨,我在我的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也花费太多时间。

这是我的索引。

enter image description here

需要帮助

c# mongodb asp.net-core mongodb-.net-driver
1个回答
0
投票

您是否尝试过AsQueryable()?并转换您的查询所需的数据。

© www.soinside.com 2019 - 2024. All rights reserved.