与 MongoDB 驱动程序 2.9.0 同步分页

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

当调用我的 API(分页)时,我需要处理返回的结果量。我在使用最新 mongo c# 驱动程序中的新异步内容来实现此目标时遇到了真正的困难。

Mongo 服务

    public class MongoService
    {
        private readonly IMongoCollection<BsonDocument> _bsondocs;

        public MongoService(IMongoDatabaseSettings settings)
        {
            //gets mongo connection string and database name from the
            //MongoDatabaseSettings class which gets it from appsettings.json
            var client = new MongoClient(settings.ConnectionString);
            var database = client.GetDatabase(settings.DatabaseName);

            //uses the name from MongoCollectionName variable, set by MongoDatabaseSettings.cs, again supplied from appsettings.json
            _bsondocs = database.GetCollection<BsonDocument>(settings.MongoCollectionName);

        }

        internal async Task<SearchResult> SearchAsync(string q, int page)
        {
            //this part performs the actual search
            var indexFilter = Builders<BsonDocument>.Filter.Text(q);

            var totalRecords = await _bsondocs.CountDocumentsAsync(indexFilter);
            //hard coded page size
            var pageSize = 20;

            var data = _bsondocs.Find(indexFilter)
                .Skip((page - 1) * pageSize)
                .Limit(pageSize);

            //create a new search result which can track the pages.
            var result = new SearchResult()
            {
                Data = data,
                CurrentPage = page,
                PageSize = pageSize,
                TotalRecords = totalRecords 
            };

            return result;
        }

        //this is the get method used by the controller to return full list of bson documents in a given DB collection.
        public List<BsonDocument> Get()
        {
            return _bsondocs.Find(bsonDocument => true).ToList();
        }

    }
}

SearchResult 类

    public class SearchResult
    {

        public int CurrentPage { get; set; }
        public int PageSize { get; set; }
        public long TotalRecords { get; set; }
        public ICollection<BsonDocument> Data { get; set; }
    }

从控制器调用

        [HttpGet("find")]
        public async Task<IActionResult> SearchText(string q, int p)
        //public ActionResult<List<BsonDocument>> SearchText(string q) =>
        {
            SearchResult result = await _mongoService.SearchAsync(q, p);

            return Ok(result);
        }

我目前遇到的错误是:

错误CS0266无法将类型“MongoDB.Driver.IFindFluent”隐式转换为“System.Collections.Generic.ICollection”。存在显式转换

但我怀疑我可能有更广泛的问题,我只能找到有关最新 mongo 驱动程序的 ASync 方法的非常有限的文档。

asp.net-mvc mongodb asp.net-core pagination c#-3.0
1个回答
2
投票

事实证明,在这种情况下,我只是缺少 find 函数上的 .ToList() 。将我的数据变量更改为以下内容解决了我的错误并使分页正常工作。

            var data = _bsondocs.Find(indexFilter)
                .Skip((page - 1) * pageSize)
                .Limit(pageSize)
                .ToList();
© www.soinside.com 2019 - 2024. All rights reserved.