zoukankan      html  css  js  c++  java
  • 【经验分享】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;
            }
            /// <summary>
            /// 数据库所在主机
            /// </summary>
            private readonly string Mongo_Conn_Host;
            /// <summary>
            /// 数据库所在主机的端口
            /// </summary>
            private readonly int Mongo_Conn_Port = 27017;
            //private readonly int Mongo_Conn_Port = 8635;
            /// <summary>
            /// 连接超时设置 秒
            /// </summary>
            private readonly string Connect_TimeOut;
    
            /// <summary>
            /// 数据库名称
            /// </summary>
            private readonly string Db_Name;
    
            /// <summary>  
            /// 得到数据库实例  
            /// </summary>  
            /// <returns></returns>  
            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 MongoDbRepository<T>where T : MongoEntityBase
        {
            public IMongoCollection<T> 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<T>(config.CollectionName);
            }
            #region +Add 添加一条数据
            public void Add(T t)
            {
                try
                {
                    this.Collection.InsertOne(t);
                }
                catch (Exception e)
                {
    
                    throw e;
                }
            }
            #endregion
    
            #region +AddAsync 异步添加一条数据
            /// <summary>
            /// 异步添加一条数据
            /// </summary>
            /// <param name="t">添加的实体</param>
            /// <param name="host">mongodb连接信息</param>
            /// <returns></returns>
            public async Task AddAsync(T t)
            {
                try
                {
                    await Collection.InsertOneAsync(t);
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
            #endregion
    
            #region +InsertMany 批量插入
            /// <summary>
            /// 批量插入
            /// </summary>
            /// <param name="host">mongodb连接信息</param>
            /// <param name="t">实体集合</param>
            /// <returns></returns>
            public void InsertMany(List<T> 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> t)
            {
                try
                {
                    if (t != null && t.Count > 0)
                    {
                        await Collection.InsertManyAsync(t);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            #endregion
    
            #region +Update 修改一条数据
            /// <summary>
            /// 修改一条数据
            /// </summary>
            /// <param name="t">添加的实体</param>
            /// <param name="host">mongodb连接信息</param>
            /// <returns></returns>
            public ReplaceOneResult UpdateOne(T t)
            {
                try
                {
                    //修改条件
                    FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", t._id);
                    //Collection.UpdateOne(filter,Builders<T>.Update)
                    return Collection.ReplaceOne(filter, t, new UpdateOptions { IsUpsert = true });
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            #endregion
    
    
            #region +UpdateManay 批量修改数据
            /// <summary>
            /// 批量修改数据
            /// </summary>
            /// <param name="dic">要修改的字段</param>
            /// <param name="host">mongodb连接信息</param>
            /// <param name="filter">修改条件</param>
            /// <returns></returns>
            public UpdateResult UpdateManay(Expression<Func<T, bool>> filter, dynamic modifyFields)
            {
                try
                {
                    var list = new List<UpdateDefinition<T>>();
                    foreach (PropertyInfo item in modifyFields.GetType().GetProperties())
                    {
                        if (item.Name.ToLower() == "id") continue;
                        list.Add(Builders<T>.Update.Set(item.Name, item.GetValue(modifyFields)));
                    }
                    return Collection.UpdateMany(filter, Builders<T>.Update.Combine(list));
                }
                catch (Exception ex)
                {
                    throw new UserFriendlyException(ex.Message);
                }
            }
            #endregion
    
            #region Delete 删除一条数据
            /// <summary>
            /// 删除一条数据
            /// </summary>
            /// <param name="host">mongodb连接信息</param>
            /// <param name="id">objectId</param>
            /// <returns></returns>
            public DeleteResult DeleteOne(ObjectId id)
            {
                try
                {
                    var filter = Builders<T>.Filter.Eq("_id", id);
                    return Collection.DeleteOne(filter);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
    
            }
            /// <summary>
            /// 删除一条数据
            /// </summary>
            /// <param name="host">mongodb连接信息</param>
            /// <param name="filter">删除条件</param>
            /// <returns></returns>
            public DeleteResult DeleteMany(Expression<Func<T, bool>> filter)
            {
                try
                {
                    return Collection.DeleteMany(filter);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
    
            }
            #endregion
    
            #region Count 根据条件获取总数
            /// <summary>
            /// 根据条件获取总数
            /// </summary>
            /// <param name="host">mongodb连接信息</param>
            /// <param name="filter">条件</param>
            /// <returns></returns>
            public long Count(Expression<Func<T, bool>> filter)
            {
                try
                {
                    return Collection.CountDocuments(filter);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            #endregion
    
    
            #region FindOne 根据id查询一条数据
            /// <summary>
            /// 根据id查询一条数据
            /// </summary>
            /// <param name="host">mongodb连接信息</param>
            /// <param name="id">objectid</param>
            /// <param name="field">要查询的字段,不写时查询全部</param>
            /// <returns></returns>
            public T FindOne(ObjectId id)
            {
                try
                {
                    return Collection.Find(x => x._id == id).FirstOrDefault<T>();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            #endregion
    
    
    
            #region FindList 查询集合
            /// <summary>
            /// 查询集合
            /// </summary>
            /// <param name="host">mongodb连接信息</param>
            /// <param name="filter">查询条件</param>
            /// <param name="field">要查询的字段,不写时查询全部</param>
            /// <param name="sort">要排序的字段</param>
            /// <returns></returns>
            public List<U> FindList<U>(Expression<Func<T, bool>> exp, Expression<Func<T, U>> select)
            {
                try
                {
                    return Collection.AsQueryable().Where(exp).Select(select).ToList();
                }
                catch (Exception ex)
                {
                    throw new UserFriendlyException(ex.Message);
                }
            }
            public List<T> FindList(Expression<Func<T, bool>> exp)
            {
                try
                {
                    return Collection.AsQueryable().Where(exp).ToList();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            #endregion
    
    
    
            #region FindListByPage 分页查询集合
            /// <summary>
            /// 分页查询集合
            /// </summary>
            /// <param name="host">mongodb连接信息</param>
            /// <param name="filter">查询条件</param>
            /// <param name="pageIndex">当前页</param>
            /// <param name="pageSize">页容量</param>
            /// <param name="count">总条数</param>
            /// <param name="field">要查询的字段,不写时查询全部</param>
            /// <param name="sort">要排序的字段</param>
            /// <returns></returns>
            public List<U> FindListByPage<U>(string field, string dir, Expression<Func<T, bool>> filter, int SkipCount, int pageSize, out long count, Expression<Func<T, U>> 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(Expression<Func<T, bool>> filter)
            {
                try
                {
                    long count = await Collection.CountDocumentsAsync(filter);
                    return count > 0;
                }
                catch (Exception ex)
                {
                    throw new UserFriendlyException(ex.Message);
                }
            }
    
            public bool Any(string collName, Expression<Func<T, bool>> 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<Customer>
    (new MongoDBConfig { CollectionName = collectionName, DbName = dbName, ConnectionString ="mongodb://localhost");
    var list=InventoryHelper.FindList(x=>true);// 得到集合所有的元素
  • 相关阅读:
    Sqli-labs Less-37 利用 ' 的utf-16突破mysql_real_escape_string()函数转义
    Sqli-labs Less-36 宽字节注入 绕过mysql_real_escape_string()函数转义
    闭包
    JavaScript(1)
    css和JavaScript
    解决奇怪的错误。访问的网页一直被拦截
    html网页乱码解决
    BZOJ 3676: [Apio2014]回文串 回文树 回文自动机
    BZOJ 3676: [Apio2014]回文串 后缀自动机 Manacher 倍增
    BZOJ 3238: [Ahoi2013]差异 后缀自动机 树形dp
  • 原文地址:https://www.cnblogs.com/wnxyz8023/p/11678075.html
Copyright © 2011-2022 走看看