Mongo帮助类(DotNet版本)

该帮助类是针对 C#语言,   我使用的驱动版本为:MongoDB.Driver为2.7.0.0版本;

使用较为简单,主要是通过对lambda进行操作,

using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Common.Data
{
    public class MongoDBHelper
    {
        private static MongoClient client;
        private static IMongoDatabase database;

        //本地配置
        private static string MongoDBConnectionStr = "mongodb://127.0.0.1:27017";

        //数据库名称
        private static string MonitorBaseName = "Monitor";


        public MongoDBHelper()
        {
            GetConnection(MonitorBaseName);
        }

        /// <summary>
        /// 构造函数 指定数据库
        /// </summary>
        /// <param name="dataBaseName"></param>
        public MongoDBHelper(string dataBaseName)
        {
            GetConnection(dataBaseName);
        }

        private static void GetConnection(string dataBaseName)
        {
            client = new MongoClient(MongoDBConnectionStr);
            database = client.GetDatabase(dataBaseName);
        }

        #region 异步插入一条数据
        /// <summary>
        /// 异步插入一条数据 无返回值
        /// </summary>
        public void Insert<T>(T obj)
        {
            InsertAsync(obj).Wait();
        }

        /// <summary>
        /// 异步插入一条数据,采用类型T的完全限定名作为collection name
        /// </summary>
        public Task InsertAsync<T>(T obj)
        {
            return InsertAsync(typeof(T).Name, obj);
        }
        /// <summary>
        /// 异步插入一条数据,手动输入collection name
        /// </summary>
        public Task InsertAsync<T>(string collectionName, T obj)
        {
            if (database == null)
            {
               
                throw new Exception("No database specified");
            }
            var collection = database.GetCollection<T>(collectionName);
            return collection.InsertOneAsync(obj);
        }
        #endregion

        #region 同步插入一条数据
        /// <summary>
        /// 同步 插入一条数据
        /// </summary>
        public void InsertOne<T>(T obj)
        {
            InsertSynch(obj);
        }

        /// <summary>
        /// 同步插入一条数据,采用类型T的完全限定名作为collection name
        /// </summary>
        public void InsertSynch<T>(T obj)
        {
            InsertSynch(typeof(T).Name, obj);
        }
        /// <summary>
        /// 同步插入一条数据,手动输入collection name
        /// </summary>
        public void InsertSynch<T>(string collectionName, T obj)
        {
            if (database == null)
            {
                throw new Exception("No database specified");
            }
            var collection = database.GetCollection<T>(collectionName);
            collection.InsertOne(obj);
        }
        #endregion


        #region 异步插入多条数据
        /// <summary>
        /// 异步 插入多条数据
        /// </summary>
        public void Insert<T>(IEnumerable<T> objs)
        {
            BatchInsertAsync(objs).Wait();
        }


        /// <summary>
        /// 异步插入多条数据,采用类型T的完全限定名作为collection name
        /// </summary>
        public Task BatchInsertAsync<T>(IEnumerable<T> objs)
        {
            return BatchInsertAsync(typeof(T).Name, objs);
        }

        /// <summary>
        /// 异步插入多条数据,手动输入collection name
        /// </summary>
        public Task BatchInsertAsync<T>(string collectionName, IEnumerable<T> objs)
        {
            if (database == null)
            {
                throw new Exception("No database specified");
            }
            if (objs == null)
            {
                throw new ArgumentException();
            }
            var collection = database.GetCollection<T>(collectionName);
            return collection.InsertManyAsync(objs);
        }


        #endregion

        #region 同步插入多条数据
        /// <summary>
        ///同步 插入多条数据
        /// </summary>
        public void InsertMany<T>(IEnumerable<T> objs)
        {
            BatchInsertSynch(objs);
        }
        /// <summary>
        /// 异步插入多条数据,采用类型T的完全限定名作为collection name
        /// </summary>
        public void BatchInsertSynch<T>(IEnumerable<T> objs)
        {
            BatchInsertSynch(typeof(T).Name, objs);
        }
        /// <summary>
        /// 异步插入多条数据,手动输入collection name
        /// </summary>
        public void BatchInsertSynch<T>(string collectionName, IEnumerable<T> objs)
        {
            if (database == null)
            {
                throw new Exception("No database specified");
            }
            if (objs == null)
            {
                throw new ArgumentException();
            }
            var collection = database.GetCollection<T>(collectionName);
            collection.InsertMany(objs);
        }



        #endregion


        #region 异步删除一条数据
        /// <summary>
        /// 异步 删除一条数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="func"></param>
        public void Delete<T>(Expression<Func<T, bool>> func)
        {
            DeleteAsync(func).Wait();
        }
        public Task DeleteAsync<T>(Expression<Func<T, bool>> obj)
        {
            return DeleteAsync(typeof(T).Name, obj);
        }
        public Task DeleteAsync<T>(string collectionName, Expression<Func<T, bool>> func)
        {
            if (database == null)
            {
                throw new Exception("No database specified");
            }
            if (func == null)
            {
                throw new ArgumentException();
            }
            var collection = database.GetCollection<T>(collectionName);
            return collection.DeleteOneAsync(func);
        }
        #endregion

        #region 同步删除一条数据
        /// <summary>
        /// 同步 删除一条数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="func"></param>
        public bool DeleteOne<T>(Expression<Func<T, bool>> func)
        {
            return DeleteSynch(func);
        }
        public bool DeleteSynch<T>(Expression<Func<T, bool>> obj)
        {
            return DeleteSynch(typeof(T).Name, obj);
        }
        public bool DeleteSynch<T>(string collectionName, Expression<Func<T, bool>> func)
        {
            if (database == null)
            {
                throw new Exception("No database specified");
            }
            if (func == null)
            {
                throw new ArgumentException();
            }
            var collection = database.GetCollection<T>(collectionName);
            var result = collection.DeleteOne(func);
            return result.IsAcknowledged == true && result.DeletedCount > 0;
        }
        #endregion


        #region 异步批量删除数据
        /// <summary>
        /// 批量删除数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="func"></param>
        public void BatchDelete<T>(Expression<Func<T, bool>> func)
        {
            BatchDeleteAsync(func).Wait();
        }
        public Task BatchDeleteAsync<T>(Expression<Func<T, bool>> obj)
        {
            return BatchDeleteAsync(typeof(T).Name, obj);
        }
        public Task BatchDeleteAsync<T>(string collectionName, Expression<Func<T, bool>> func)
        {
            if (database == null)
            {
                throw new Exception("No database specified");
            }
            if (func == null)
            {
                throw new ArgumentException();
            }
            var collection = database.GetCollection<T>(collectionName);
            return collection.DeleteManyAsync(func);
        }
        #endregion

        #region 同步批量删除数据
        /// <summary>
        /// 批量删除数据  同步 有返回结果
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="func"></param>
        public bool BatchDeleteMany<T>(Expression<Func<T, bool>> func)
        {
            return BatchDeleteSynch(func);
        }
        public bool BatchDeleteSynch<T>(Expression<Func<T, bool>> obj)
        {
            return BatchDeleteSynch(typeof(T).Name, obj);
        }
        public bool BatchDeleteSynch<T>(string collectionName, Expression<Func<T, bool>> func)
        {
            if (database == null)
            {
                throw new Exception("No database specified");
            }
            if (func == null)
            {
                throw new ArgumentException();
            }
            var collection = database.GetCollection<T>(collectionName);
            var result = collection.DeleteMany(func);
            return result.IsAcknowledged == true && result.DeletedCount > 0;
        }
        #endregion


        #region  异步更新一条数据
        /// <summary>
        /// 异步 更新一条数据 无返回结果
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="func"></param>
        /// <param name="updated"></param>
        /// <returns></returns>
        public void Update<T>(Expression<Func<T, bool>> func, UpdateDefinition<T> updated)
        {
            UpdateAsync(func, updated).Wait();
        }
        public Task UpdateAsync<T>(Expression<Func<T, bool>> func, UpdateDefinition<T> updated)
        {
            return UpdateAsync(typeof(T).Name, func, updated);
        }
        public Task UpdateAsync<T>(string collectionName, Expression<Func<T, bool>> func, UpdateDefinition<T> updated)
        {
            if (database == null)
            {
                throw new Exception("No database specified");
            }
            if (func == null)
            {
                throw new ArgumentException();
            }
            var collection = database.GetCollection<T>(collectionName);
            return collection.UpdateOneAsync(func, updated);
        }
        #endregion

        #region 同步更新一条数据
        /// <summary>
        /// 同步更新一条数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="func">lambda表达式条件</param>
        /// <param name="updated">更新内容</param>
        /// <returns></returns>
        public bool UpdateOne<T>(Expression<Func<T, bool>> func, UpdateDefinition<T> updated)
        {
            return UpdateSynch(func, updated);
        }
        public bool UpdateSynch<T>(Expression<Func<T, bool>> func, UpdateDefinition<T> updated)
        {
            return UpdateSynch(typeof(T).Name, func, updated);
        }
        public bool UpdateSynch<T>(string collectionName, Expression<Func<T, bool>> func, UpdateDefinition<T> updated)
        {
            if (database == null)
            {
                throw new Exception("No database specified");
            }
            if (func == null)
            {
                throw new ArgumentException();
            }
            var collection = database.GetCollection<T>(collectionName);
            var result = collection.UpdateOne(func, updated);
            return result.IsAcknowledged == true && result.ModifiedCount > 0;
        }
        #endregion


        #region  异步更新多条数据
        /// <summary>
        /// 异步 更新一条数据 无返回结果
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="func"></param>
        /// <param name="updated"></param>
        /// <returns></returns>
        public void BatchUpdate<T>(Expression<Func<T, bool>> func, UpdateDefinition<T> updated)
        {
            BatchUpdateAsync(func, updated).Wait();
        }
        public Task BatchUpdateAsync<T>(Expression<Func<T, bool>> func, UpdateDefinition<T> updated)
        {
            return BatchUpdateAsync(typeof(T).Name, func, updated);
        }
        public Task BatchUpdateAsync<T>(string collectionName, Expression<Func<T, bool>> func, UpdateDefinition<T> updated)
        {
            if (database == null)
            {
                throw new Exception("No database specified");
            }
            if (func == null)
            {
                throw new ArgumentException();
            }
            var collection = database.GetCollection<T>(collectionName);
            return collection.UpdateManyAsync(func, updated);
        }
        #endregion

        #region 同步更新多条数据
        /// <summary>
        /// 同步更新多条数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="func">lambda表达式条件</param>
        /// <param name="updated">更新内容</param>
        /// <returns></returns>
        public bool UpdateMany<T>(Expression<Func<T, bool>> func, UpdateDefinition<T> updated)
        {
            return BatchUpdateSynch(func, updated);
        }
        public bool BatchUpdateSynch<T>(Expression<Func<T, bool>> func, UpdateDefinition<T> updated)
        {
            return BatchUpdateSynch(typeof(T).Name, func, updated);
        }
        public bool BatchUpdateSynch<T>(string collectionName, Expression<Func<T, bool>> func, UpdateDefinition<T> updated)
        {
            if (database == null)
            {
                throw new Exception("No database specified");
            }
            if (func == null)
            {
                throw new ArgumentException();
            }
            var collection = database.GetCollection<T>(collectionName);
            var result = collection.UpdateMany(func, updated);
            return result.IsAcknowledged == true && result.ModifiedCount > 0;
        }
        #endregion

        /// <summary>
        /// MongoDB C# Driver的Find方法,返回IFindFluent。手动输入collection name
        /// </summary>
        /// IFindFluent < TDocument,TProjection >
        public IFindFluent<T, T> Find<T>(string collectionName, FilterDefinition<T> filter, FindOptions options = null)
        {
            if (database == null)
            {
                throw new Exception("No database specified");
            }
            var collection = database.GetCollection<T>(collectionName);
            return collection.Find(filter, options);
        }

        /// <summary>
        /// MongoDB C# Driver的Find方法,返回IFindFluent。采用类型T的完全限定名作为collection name
        /// </summary>
        public IFindFluent<T, T> Find<T>(FilterDefinition<T> filter, FindOptions options = null)
        {
            return Find(typeof(T).Name, filter, options);
        }

        /// <summary>
        /// 取符合条件的数据 sort中多个排序条件逗号分隔,默认asc
        /// </summary>
        public List<T> Get<T>(Expression<Func<T, bool>> condition, int skip, int limit, string sort)
        {
            return Get(new List<Expression<Func<T, bool>>> { condition }, skip, limit, sort);
        }

        public List<T> Get<T>(Expression<Func<T, bool>> condition)
        {
            return Get(condition, 0, 0, null);
        }

        /// <summary>
        /// 取符合条件的数据 sort中多个排序条件逗号分隔,默认asc
        /// </summary>
        public List<T> Get<T>(List<Expression<Func<T, bool>>> conditions, int skip, int limit, string sort)
        {
            if (conditions == null || conditions.Count == 0)
            {
                conditions = new List<Expression<Func<T, bool>>> { x => true };
            }
            var builder = Builders<T>.Filter;
            var filter = builder.And(conditions.Select(x => builder.Where(x)));

            var ret = new List<T>();
            try
            {
                List<SortDefinition<T>> sortDefList = new List<SortDefinition<T>>();
                if (sort != null)
                {
                    var sortList = sort.Split(',');
                    for (var i = 0; i < sortList.Length; i++)
                    {
                        var sl = Regex.Replace(sortList[i].Trim(), @"\s+", " ").Split(' ');
                        if (sl.Length == 1 || (sl.Length >= 2 && sl[1].ToLower() == "asc"))
                        {
                            sortDefList.Add(Builders<T>.Sort.Ascending(sl[0]));
                        }
                        else if (sl.Length >= 2 && sl[1].ToLower() == "desc")
                        {
                            sortDefList.Add(Builders<T>.Sort.Descending(sl[0]));
                        }
                    }
                }
                var sortDef = Builders<T>.Sort.Combine(sortDefList);
                ret = Find(filter).Sort(sortDef).Skip(skip).Limit(limit).ToListAsync().Result;
            }
            catch (Exception e)
            {
                //异常处理
            }
            return ret;
        }

        public List<T> Get<T>(List<Expression<Func<T, bool>>> conditions)
        {
            return Get(conditions, 0, 0, null);
        }
    }
}

  希望能对各位朋友有所帮助。

猜你喜欢

转载自www.cnblogs.com/HubertBiyo/p/9285225.html
今日推荐