c# MongoHelper MongoDB操作类

using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
/*****************************
 * 概要:Mongodb操作类
 * 设计者:DuanXuWen
 * 设计时间:20181108
 * 版本:0.1
 * 修改者:
 * 修改时间:
 * ***************************/

namespace MongoWebApplication.Common
{
    public class MongoHelper
    {
        #region 配置信息

        private static string connectionStr = string.Empty;

        public static string ConnectionStr
        {
            get
            {
                if (string.IsNullOrEmpty(connectionStr))
                {
                    connectionStr = "mongodb://" + ConfigurationManager.AppSettings["MongoIp"] + ":" + ConfigurationManager.AppSettings["MongoPort"] + "/?safe=true";
                }
                return connectionStr;
            }
            set
            {
                connectionStr = value;
            }
        }

        private static MongoServer mongoServer = null;

        public static MongoServer MongoServer
        {
            get
            {
                if (mongoServer == null)
                {
                    mongoServer = new MongoClient(MongoUrl.Create(ConnectionStr)).GetServer();
                }
                return mongoServer;
            }
            set
            {
                mongoServer = value;
            }
        }

        #endregion

        #region 新增表数据

        /// 
        /// 添加数据[Insert]
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static async Task AddTableData(string databaseName, string collectionName, T entity)
        {
            SafeModeResult result = new SafeModeResult(null);
            await Task.Run(() =>
            {
                try
                {
                    MongoDatabase database = MongoServer.GetDatabase(databaseName);
                    using (MongoServer.RequestStart(database))
                    {
                        MongoCollection myCollection = database.GetCollection(collectionName);
                        result = myCollection.Insert(entity);
                    }
                }
                catch (Exception ex)
                {
                    string parameters = string.Format("【databaseName:{0}】【collectionName:{1}】【entity:{2}】", databaseName, collectionName, Newtonsoft.Json.JsonConvert.SerializeObject(entity).ToString());
                    Common.LogHelper.WriteLog(ex, "此异常由Web服务发起!接口描述:[Insert]。参数详情:" + parameters);
                }
                if (!string.IsNullOrEmpty(result.ErrorMessage))
                {
                    string parameters = string.Format("【databaseName:{0}】【collectionName:{1}】【entity:{2}】", databaseName, collectionName, Newtonsoft.Json.JsonConvert.SerializeObject(entity).ToString());
                    Common.LogHelper.WriteLog(null, "此异常由Mongo发起!接口描述:[Insert]。详情:" + result.ErrorMessage.ToString() + "。参数详情:" + parameters);
                }
            });
            return result.Ok;
        }

        /// 
        /// 添加数据[InsertBatch]
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static IEnumerable AddTableDatas(string databaseName, string collectionName, IEnumerable entitys)
        {
            IEnumerable result = null;
            try
            {
                MongoDatabase database = MongoServer.GetDatabase(databaseName);
                using (MongoServer.RequestStart(database))
                {
                    MongoCollection myCollection = database.GetCollection(collectionName);
                    result = myCollection.InsertBatch(entitys);
                }
            }
            catch (Exception ex)
            {
                string parameters = string.Format("【databaseName:{0}】【collectionName:{1}】【entitys:{2}】", databaseName, collectionName, Newtonsoft.Json.JsonConvert.SerializeObject(entitys).ToString());
                Common.LogHelper.WriteLog(ex, "此异常由Web服务发起!接口描述:[InsertBatch]。参数详情:" + parameters);
            }
            return result;
        }

        #endregion

        #region 修改表数据

        /// 
        /// 修改数据[Update]
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static async Task UpdateTableData(string databaseName, string collectionName, string name, string value, string newName, string newValue)
        {
            SafeModeResult result = new SafeModeResult(null);
            await Task.Run(() =>
            {
                try
                {
                    MongoDatabase database = MongoServer.GetDatabase(databaseName);
                    using (MongoServer.RequestStart(database))
                    {
                        MongoCollection myCollection = database.GetCollection(collectionName);
                        var query = Query.EQ(name, value);
                        var update = new UpdateDocument { { "$set", new QueryDocument { { newName, newValue } } } };
                        result = myCollection.Update(query, update);
                    }
                }
                catch (Exception ex)
                {
                    string parameters = string.Format("【databaseName:{0}】【collectionName:{1}】【name:{2}】【value:{3}】【newName:{4}】【newValue:{5}】", databaseName, collectionName, name, value, newName, newValue);
                    Common.LogHelper.WriteLog(ex, "此异常由Web服务发起!接口描述:[Update]。参数详情:" + parameters);
                }
                if (!string.IsNullOrEmpty(result.ErrorMessage))
                {
                    string parameters = string.Format("【databaseName:{0}】【collectionName:{1}】【name:{2}】【value:{3}】【newName:{4}】【newValue:{5}】", databaseName, collectionName, name, value, newName, newValue);
                    Common.LogHelper.WriteLog(null, "此异常由Mongo发起!接口描述:[Update]。详情:" + result.ErrorMessage.ToString() + "。参数详情:" + parameters);
                }
            });
            return result.Ok;
        }

        #endregion

        #region 删除表数据

        /// 
        /// 删除数据[Delete]
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static async Task DeleteTableData(string databaseName, string collectionName, string name, string value)
        {
            SafeModeResult result = new SafeModeResult(null);
            await Task.Run(() =>
            {
                try
                {
                    MongoDatabase database = MongoServer.GetDatabase(databaseName);
                    using (MongoServer.RequestStart(database))
                    {
                        MongoCollection myCollection = database.GetCollection(collectionName);
                        result = myCollection.Remove(Query.EQ(name, value));
                    }
                }
                catch (Exception ex)
                {
                    string parameters = string.Format("【databaseName:{0}】【collectionName:{1}】【name:{2}】【value:{3}】", databaseName, collectionName, name, value);
                    Common.LogHelper.WriteLog(ex, "此异常由Web服务发起!接口描述:[Delete]。参数详情:" + parameters);
                }
                if (!string.IsNullOrEmpty(result.ErrorMessage))
                {
                    string parameters = string.Format("【databaseName:{0}】【collectionName:{1}】【name:{2}】【value:{3}】", databaseName, collectionName, name, value);
                    Common.LogHelper.WriteLog(null, "此异常由Mongo发起!接口描述:[Delete]。详情:" + result.ErrorMessage.ToString() + "。参数详情:" + parameters);
                }
            });
            return result.Ok;
        }

        #endregion

        #region 查询表数据

        /// 
        /// 查询数据[Select]
        /// 
        /// 
        /// 
        /// 
        /// 
        public static async Task> SelectTableData(string databaseName, string collectionName)
        {
            List result = new List();
            await Task.Run(() =>
            {
                try
                {
                    MongoDatabase database = MongoServer.GetDatabase(databaseName);
                    using (MongoServer.RequestStart(database))
                    {
                        MongoCollection myCollection = database.GetCollection(collectionName);
                        result.AddRange(myCollection.FindAll());
                    }
                }
                catch (Exception ex)
                {
                    string parameters = string.Format("【databaseName:{0}】【collectionName:{1}】", databaseName, collectionName);
                    Common.LogHelper.WriteLog(ex, "此异常由Web服务发起!接口描述:[Select]。参数详情:" + parameters);
                }
            });
            return result;
        }

        #endregion
    }
}

 

你可能感兴趣的:(c#)