创建一个获取MongoDB数据库实例的类
public class Db { private static IMongoDatabase db = null; private static readonly object lockHelper = new object(); private Db() { } public static IMongoDatabase GetDb(string connStr, string dbName) { if (db == null) { lock (lockHelper) { if (db == null) { var client = new MongoClient(connStr); db = client.GetDatabase(dbName); } } } return db; } }
创建一个操作MongDB的辅助类
public class MongoDbHelper<T> where T : MongoBaseEntity, new() { private IMongoDatabase db = null; private IMongoCollection<T> collection = null; private readonly IOptions<MongoDBConfig> _options; public MongoDbHelper(IOptions<MongoDBConfig> options) { this._options = options; this.db = Db.GetDb(this._options.Value.ConnectionString, this._options.Value.DbName); collection = db.GetCollection<T>(typeof(T).Name); } /// <summary> /// 分页 /// </summary> /// <param name="filter"></param> /// <param name="sort"></param> /// <param name="pageIndex"></param> /// <param name="pageSize"></param> /// <returns></returns> public PagingModel<T> GetPagingData(FilterDefinition<T> filter, SortDefinition<T> sort, int pageIndex, int pageSize) { var list = collection .Find(filter) .Sort(sort) .Skip((pageIndex - 1) * pageSize) .Limit(pageSize) .ToList(); var count = collection.CountDocuments(filter); var pagingModel = new PagingModel<T>(); pagingModel.Items = list; pagingModel.PageIndex = pageIndex; pagingModel.PageSize = pageSize; pagingModel.TotalRecords = Convert.ToInt32(count); pagingModel.TotalPages = (int)Math.Ceiling((double)count / (double)pageSize); return pagingModel; }
创建一个分页实体类
/// <summary> /// 描述:分页实体 /// 创建人:苏本东 /// 创建时间:2019-3-5 19:05:20 /// </summary> /// <typeparam name="T"></typeparam> public class PagingModel<T> where T : class, new() { /// <summary> /// 当前页码 /// </summary> public int PageIndex { get; set; } /// <summary> /// 每页大小 /// </summary> public int PageSize { get; set; } /// <summary> /// 总记录数 /// </summary> public int TotalRecords { get; set; } /// <summary> /// 总页数 /// </summary> public int TotalPages { get; set; } /// <summary> /// 每页数据 /// </summary> public List<T> Items { get; set; } }
最后就是调用了
FilterDefinition<ModbusData> filter = Builders<ModbusData>.Filter.Empty; if (request.Ip.IsNotNullAndEmpty()) { //注意:Eq方法的第一个参数,大小写需要跟数据库一致,不然查询无效 filter = Builders<ModbusData>.Filter.Eq("IP", request.Ip); } var sort = Builders<ModbusData>.Sort.Descending(c => c._id); var pagingModel = this._mongo.GetPagingData(filter, sort, (int)request.page, (int)request.limit);