【经验分享】Mongodb操作类实现CRUD

一.背景

公司项目中在做数据存储时使用到Mongodb,所以想着将Mongodb的操作封装后可供项目中其他成员方便使用。

附上Mongodb的下载地址: 下载

1.Mongodb类 此类主要是用来构造Mongodb数据库实例的。

 public class MongoDb
    {
        public MongoDb(string host, string DbName, string timeOut)
        {
            this.Connect_TimeOut = timeOut;
            this.Mongo_Conn_Host = host;
            this.Db_Name = DbName;
        }
        /// 
        /// 数据库所在主机
        /// 
        private readonly string Mongo_Conn_Host;
        /// 
        /// 数据库所在主机的端口
        /// 
        private readonly int Mongo_Conn_Port = 27017;
        //private readonly int Mongo_Conn_Port = 8635;
        /// 
        /// 连接超时设置 秒
        /// 
        private readonly string Connect_TimeOut;

        /// 
        /// 数据库名称
        /// 
        private readonly string Db_Name;

        ///   
        /// 得到数据库实例  
        ///   
        ///   
        public IMongoDatabase GetDataBase()
        {

            MongoClientSettings mongoSetting = new MongoClientSettings();
            //设置连接超时时间  
            //mongoSetting.ConnectTimeout = new TimeSpan(int.Parse(Connect_TimeOut) * TimeSpan.TicksPerSecond);
            mongoSetting.ConnectTimeout = TimeSpan.FromSeconds(1000);
            //设置数据库服务器  
            mongoSetting.Server = new MongoServerAddress(Mongo_Conn_Host, Mongo_Conn_Port);

            //创建Mongo的客户端  
            MongoClient client = new MongoClient(mongoSetting);
            //得到服务器端并且生成数据库实例  
            return client.GetDatabase(Db_Name);
        }
    }

2.MongoEntityBase类 包含Mongodb的主键 _id

    public class MongoEntityBase
    {
        public ObjectId _id { get; set; }

    }

3.MongodbConfig类,包含Mongodb的连接地址,数据库名称和集合名称

    public class MongoDBConfig
    {
        public string ConnectionString { get; set; }
        public string DbName { get; set; }
        public string CollectionName { get; set; }
    }

4.MongodbRepository泛型类,传入要操作的对象实现CRUD

  public class MongoDbRepositorywhere T : MongoEntityBase
    {
        public IMongoCollection Collection { get; private set; }
        public IMongoDatabase Database { get; private set; }

        public MongoDbRepository(MongoDBConfig config)
        {
            Database = new MongoClient(config.ConnectionString).GetDatabase(config.DbName);
            Collection = Database.GetCollection(config.CollectionName);
        }
        #region +Add 添加一条数据
        public void Add(T t)
        {
            try
            {
                this.Collection.InsertOne(t);
            }
            catch (Exception e)
            {

                throw e;
            }
        }
        #endregion

        #region +AddAsync 异步添加一条数据
        /// 
        /// 异步添加一条数据
        /// 
        /// 添加的实体
        /// mongodb连接信息
        /// 
        public async Task AddAsync(T t)
        {
            try
            {
                await Collection.InsertOneAsync(t);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        #endregion

        #region +InsertMany 批量插入
        /// 
        /// 批量插入
        /// 
        /// mongodb连接信息
        /// 实体集合
        /// 
        public void InsertMany(List t)
        {
            try
            {
                if (t != null && t.Count > 0)
                {
                    Collection.InsertMany(t);
                }
            }
            catch (Exception ex)
            {
                throw new UserFriendlyException(ex.Message);
            }
        }
        public async Task InsertManyAsync(List t)
        {
            try
            {
                if (t != null && t.Count > 0)
                {
                    await Collection.InsertManyAsync(t);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region +Update 修改一条数据
        /// 
        /// 修改一条数据
        /// 
        /// 添加的实体
        /// mongodb连接信息
        /// 
        public ReplaceOneResult UpdateOne(T t)
        {
            try
            {
                //修改条件
                FilterDefinition filter = Builders.Filter.Eq("_id", t._id);
                //Collection.UpdateOne(filter,Builders.Update)
                return Collection.ReplaceOne(filter, t, new UpdateOptions { IsUpsert = true });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion


        #region +UpdateManay 批量修改数据
        /// 
        /// 批量修改数据
        /// 
        /// 要修改的字段
        /// mongodb连接信息
        /// 修改条件
        /// 
        public UpdateResult UpdateManay(Expressionbool>> filter, dynamic modifyFields)
        {
            try
            {
                var list = new List>();
                foreach (PropertyInfo item in modifyFields.GetType().GetProperties())
                {
                    if (item.Name.ToLower() == "id") continue;
                    list.Add(Builders.Update.Set(item.Name, item.GetValue(modifyFields)));
                }
                return Collection.UpdateMany(filter, Builders.Update.Combine(list));
            }
            catch (Exception ex)
            {
                throw new UserFriendlyException(ex.Message);
            }
        }
        #endregion

        #region Delete 删除一条数据
        /// 
        /// 删除一条数据
        /// 
        /// mongodb连接信息
        /// objectId
        /// 
        public DeleteResult DeleteOne(ObjectId id)
        {
            try
            {
                var filter = Builders.Filter.Eq("_id", id);
                return Collection.DeleteOne(filter);
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        /// 
        /// 删除一条数据
        /// 
        /// mongodb连接信息
        /// 删除条件
        /// 
        public DeleteResult DeleteMany(Expressionbool>> filter)
        {
            try
            {
                return Collection.DeleteMany(filter);
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        #endregion

        #region Count 根据条件获取总数
        /// 
        /// 根据条件获取总数
        /// 
        /// mongodb连接信息
        /// 条件
        /// 
        public long Count(Expressionbool>> filter)
        {
            try
            {
                return Collection.CountDocuments(filter);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion


        #region FindOne 根据id查询一条数据
        /// 
        /// 根据id查询一条数据
        /// 
        /// mongodb连接信息
        /// objectid
        /// 要查询的字段,不写时查询全部
        /// 
        public T FindOne(ObjectId id)
        {
            try
            {
                return Collection.Find(x => x._id == id).FirstOrDefault();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion



        #region FindList 查询集合
        /// 
        /// 查询集合
        /// 
        /// mongodb连接信息
        /// 查询条件
        /// 要查询的字段,不写时查询全部
        /// 要排序的字段
        /// 
        public List FindList(Expressionbool>> exp, Expression> select)
        {
            try
            {
                return Collection.AsQueryable().Where(exp).Select(select).ToList();
            }
            catch (Exception ex)
            {
                throw new UserFriendlyException(ex.Message);
            }
        }
        public List FindList(Expressionbool>> exp)
        {
            try
            {
                return Collection.AsQueryable().Where(exp).ToList();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion



        #region FindListByPage 分页查询集合
        /// 
        /// 分页查询集合
        /// 
        /// mongodb连接信息
        /// 查询条件
        /// 当前页
        /// 页容量
        /// 总条数
        /// 要查询的字段,不写时查询全部
        /// 要排序的字段
        /// 
        public List FindListByPage(string field, string dir, Expressionbool>> filter, int SkipCount, int pageSize, out long count, Expression> select)
        {
            try
            {
                count = Collection.CountDocuments(filter);
                var query = Collection.AsQueryable().Where(filter).OrderBy(field, dir);
                var data = query.Skip(SkipCount).Take(pageSize).Select(select).ToList();
                return data;
            }
            catch (Exception ex)
            {
                throw new UserFriendlyException(ex.Message);
            }
        }

        #endregion

        public async Task<bool> AnyAsync(Expressionbool>> filter)
        {
            try
            {
                long count = await Collection.CountDocumentsAsync(filter);
                return count > 0;
            }
            catch (Exception ex)
            {
                throw new UserFriendlyException(ex.Message);
            }
        }

        public bool Any(string collName, Expressionbool>> filter)
        {
            try
            {
                long count = Collection.CountDocuments(filter);
                return count > 0;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

    }
View Code

 5.初始化MongodbHelper

  string dbName = "测试CRUD";
  string collectionName ="mongdb";
  var InventoryHelper = new MongoDbRepository
(new MongoDBConfig { CollectionName = collectionName, DbName = dbName, ConnectionString ="mongodb://localhost");
var list=InventoryHelper.FindList(x=>true);// 得到集合所有的元素

 

你可能感兴趣的:(【经验分享】Mongodb操作类实现CRUD)