• c# MongoDB分页辅助类,支持多条件查询


    创建一个获取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);
                this.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 = this.collection
                    .Find(filter)
                    .Sort(sort)
                    .Skip((pageIndex - 1) * pageSize)
                    .Limit(pageSize)
                    .ToList();
    
                var count = this.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;
            }
        }

    说明:构造方法public MongoDbHelper(IOptions<MongoDBConfig> options)中的参数,是与配置文件中的MongoDBConfig节点对应的,我的项目是.net core项目。 

    下面是appsettings.json配置文件部分代码:

      "MongoDBConfig": {
        "ConnectionString": "mongodb://xxx:xxx@192.168.3.240:27017",
        "DbName": "xxxDB"
      }
        public class MongoDBConfig
        {
            /// <summary>
            /// 数据库连接字符串
            /// </summary>
            public string ConnectionString { get; set; }
    
            /// <summary>
            /// 具体数据库名称
            /// </summary>
            public string DbName { get; set; }
        }

    创建一个分页实体类

        /// <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);

    ModbusData类是与MongoDB的表对应的

    提供两篇文章供学习参考:

    https://www.cnblogs.com/quebra/p/10202449.html

    https://www.cnblogs.com/woxpp/p/6347429.html

  • 相关阅读:
    数据库的规范和SQL优化技巧总结
    新版Intellij idea破解方法(插件IDE Eval Reset)
    容易遗忘的知识点总结
    Java如何搭建脚手架(自动生成通用代码),创建自定义的archetype(项目模板)
    阿里云服务器域名解析和ICP域名备案
    云服务器通过ip无法访问
    FirewallD is not running 远程服务器开启端口报错
    [prerender-spa-plugin] Unable to prerender all routes! 内网打包报错(Navigation Timeout Exceeded)
    vue-cli中的 mode模式、env环境文件,以及其中定义的环境变量
    绘制柱状图和横向条形图,带数据标签!!!
  • 原文地址:https://www.cnblogs.com/subendong/p/11818170.html
Copyright © 2020-2023  润新知