// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。 // // 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。 // // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任! using MongoDB.Bson; using MongoDB.Driver; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; public class MongoPagination { private readonly IMongoCollection _collection; private readonly FilterDefinition _filter; private readonly SortDefinition _sort; private readonly int _pageSize; private readonly int _currentPage; public MongoPagination(IMongoCollection collection, FilterDefinition filter, SortDefinition sort, int pageSize, int currentPage) { _collection = collection; _filter = filter ?? new BsonDocument(); // 如果没有过滤器,则使用空过滤器 _sort = sort ?? Builders.Sort.Ascending(default(string)); // 如果没有排序,则使用默认升序排序 _pageSize = pageSize; _currentPage = currentPage; } public async Task<(List Items, long TotalCount, int TotalPages)> GetPagedDataAsync() { // 计算总记录数 long totalCount = await _collection.CountDocumentsAsync(_filter); // 计算总页数 int totalPages = (int)Math.Ceiling((double)totalCount / _pageSize); // 跳过之前的页数并获取当前页的数据 var skip = (_currentPage - 1) * _pageSize; var items = await _collection .Find(_filter) .Sort(_sort) .Skip(skip) .Limit(_pageSize) .ToListAsync(); return (items, totalCount, totalPages); } }