• MongoDbHelper 帮助类(下)


    对MongoDbHelper帮助类进行了一下整合,但是代码中一个方法需要将string类型转化为BsonValue类型一直出错。所以欢迎留言指正

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using MongoDB.Driver;
    using MongoDB.Bson;
    using MongoDB.Driver.Builders;
    using System.Text.RegularExpressions;
    namespace Web.MondbHelp
    {
        /// <summary>
        /// mongodb的封装类。
        /// </summary>
        public class MongoDBHelper<T>
        {
            //获取web.config中的配置
            public static readonly string connectionString_Default = System.Configuration.ConfigurationManager.AppSettings["ConnectionString_mongoDB"];// mongodb://192.168.1.103:27017/test
            public static readonly string database_Default = System.Configuration.ConfigurationManager.AppSettings["Database_mongoDB"]; //test
    
            #region MongoService
            private string Database { get { return database_Default; } }
            private string Connection { get { return connectionString_Default; } }
    
            private string collectName
            {
                get
                {
                    return typeof(T).Name;
                }
            }
    
            private MongoServer GetService(string conn)
            {
                var client = new MongoClient(conn);
                return client.GetServer();
            }
    
            protected MongoServer GetServer()
            {
                return GetService(Connection);
            }
            protected MongoDatabase GetDatabase()
            {
                return GetServer().GetDatabase(Database);
            }
    
            public MongoCollection GetCollection()
            {
                var service = GetServer();
                var database = GetDatabase();
                //using (service.RequestStart(database))
                //{
                //    MongoCollection<T> mycollection = database.GetCollection<T>(collectName);
                //    return mycollection;
                //}
    
                if (!database.CollectionExists(collectName))
                    database.CreateCollection(collectName);
                return database.GetCollection(collectName);
            }
            #endregion
    
            #region 自己重新封装方法
            #region 保存
            /// <summary>
            /// 添加
            /// </summary>
            /// <param name="t"></param>
            /// <returns></returns>
            protected bool Insert(T t)
            {
                var result = GetCollection().Insert<T>(t);
                return result.Ok;
            }
    
            protected void BatchInsert(IList<T> list)
            {
                GetCollection().InsertBatch(list);
            }
    
            protected bool Save(T t)
            {
                var result = GetCollection().Save<T>(t);
                return result.Ok;
            }
            #endregion
            #region 修改
            protected bool Update(IMongoQuery query, IMongoUpdate update, UpdateFlags flags = UpdateFlags.None)
            {
                var result = GetCollection().Update(query, update, flags);
                return result.Ok;
            }
            protected bool Update(string id, T t)
            {
                var doc = new UpdateDocument(BsonExtensionMethods.ToBsonDocument(t));
                return GetCollection().Update(Query.EQ("_id", id), doc).Ok;
            }
            protected bool FindAndModify(string id, Dictionary<string, object> Updates)
            {
                UpdateBuilder builder = null;
                foreach (var v in Updates)
                {
                    BsonValue value = v.Value.ToString();
                    builder.AddToSet(v.Key, value.AsBsonValue);//此处的转换错误一直没解决掉
                }
                return GetCollection().Update(Query.EQ("_id", id), builder).Ok;
            }
            //protected bool Update(string[] ids, Dictionary<string, object> updates)
            //{
            //    return GetCollection().FindAndModify .FindAndModify<T>(Query.In("_id", ToBsonArray(ids)), updates);
            //}
            //protected bool Update(string[] ids, string field, object value)
            //{
            //    return Update(ids, new Dictionary<string, object> { { field, value } });
            //}
            //protected bool Update(string id, string field, object value)
            //{
            //    return Update(id, new Dictionary<string, object> { { field, value } });
            //}
            //protected bool Update(string id, Dictionary<string, object> updates)
            //{
            //    return GetCollection().FindAndModify<T>(id, updates);
            //}
            #endregion
            #region 删除
            protected bool Remove(IMongoQuery query)
            {
                var result = GetCollection().Remove(query);
                return result.Ok;
            }
            protected void RemoveByIds(string[] ids)
            {
                var query = Query.In("_id", ToBsonArray(ids));
                GetCollection().Remove(query);
            }
            protected void RemoveById(string id)
            {
                RemoveByIds(new string[1] { id });
            }
            #endregion
            #region 查询
            /// <summary>
            /// 判断数据是否存在
            /// </summary>
            /// <param name="id"></param>
            /// <returns></returns>
            protected bool IsExists(string id)
            {
                return Count(Query.EQ("_id", id)) > 0;
            }
    
            /// <summary>
            /// 查询数量
            /// </summary>
            /// <param name="query"></param>
            /// <returns></returns>
            protected long Count(IMongoQuery query)
            {
                return GetCollection().Count(query);
            }
            protected IList<BsonValue> Distict(string key, IMongoQuery query)
            {
                return GetCollection().Distinct(key, query).ToList();
            }
            protected T FindOneById(string id, params string[] fields)
            {
                var query = Query.EQ("_id", id);
                return FindOne(query, fields);
            }
            public T FindOne(IMongoQuery query, params string[] fields)
            {
                var result = Find(1, query, SortBy.Null, fields);
                if (result.Count > 0)
                {
                    return result.FirstOrDefault();
                }
                return default(T);
            }
            public IList<T> FindAll(params string[] fields)
            {
                var cursor = GetCollection().FindAllAs<T>().SetFlags(QueryFlags.NoCursorTimeout);
                if (fields != null && fields.Length > 0)
                {
                    cursor.SetFields(fields);
                }
                return cursor.ToList();
            }
            public IList<T> FindByIds(IEnumerable<string> ids, params string[] fields)
            {
                return Find(Query.In("_id", ToBsonArray(ids)));
            }
            protected IList<T> Find(IMongoQuery query, params string[] fields)
            {
                return Find(query, SortBy.Null, fields);
            }
            protected IList<T> Find(IMongoQuery query, IMongoSortBy sortBy, params string[] fields)
            {
                return Find(0, query, sortBy, fields);
            }
            protected IList<T> Find(int topCount, IMongoQuery query, params string[] fields)
            {
                return Find(topCount, query, fields);
            }
            protected IList<T> Find(int topCount, IMongoQuery query, IMongoSortBy sortBy, params string[] fields)
            {
                var cursor = GetCollection().FindAs<T>(query);
                if (topCount > 0)
                {
                    cursor.SetLimit(topCount);
                }
                if (sortBy != null && sortBy != SortBy.Null)
                {
                    cursor.SetSortOrder(sortBy);
                }
                if (fields != null && fields.Length > 0)
                {
                    cursor.SetFields(fields);
                }
                return cursor.ToList();
            }
            #endregion
            #region 分页
            /// <summary>
            ///  数据量大时 性能不好
            /// </summary>
            /// <param name="query"></param>
            /// <param name="sortBy"></param>
            /// <param name="page"></param>
            /// <param name="size"></param>
            /// <param name="totalCount"></param>
            /// <param name="fields"></param>
            /// <returns></returns>
            protected IList<T> FindPage(IMongoQuery query, IMongoSortBy sortBy, int page, int size, out long totalCount, params string[] fields)
            {
                int skipCount = 0;
                if (page > 1)
                    skipCount = (page - 1) * size;
                else
                    page = 1;
    
                totalCount = Count(query);
                var list = new List<T>();
    
                if (totalCount > 0)
                    list = GetCollection().FindAs<T>(query).SetFlags(QueryFlags.NoCursorTimeout).SetSortOrder(sortBy).SetSkip(skipCount).SetLimit(size).SetFields(fields).ToList();
                return list;
            }
    
            protected IList<T> FindPage(string lastObjId, IMongoQuery query, int pageSize,
               out long totalCount, params string[] fields)
            {
                return FindPage(lastObjId, query, pageSize, out totalCount, true, fields);
            }
            protected IList<T> FindPage(string lastObjId, IMongoQuery query, int pageSize, params string[] fields)
            {
                long totalCount;
                return FindPage(lastObjId, query, pageSize, out totalCount, false, fields);
            }
    
            /// <summary>
            /// 获取前一页的最后一条记录,查询之后的指定条记录 
            /// </summary>
            /// <param name="lastObjId">首次加载为string.Emtpy,当前页最后一条数据的Id</param>
            /// <param name="query"></param>
            /// <param name="size"></param>
            /// <param name="totalCount"></param>
            /// <param name="isOutTotalCount"></param>
            /// <param name="fields"></param>
            /// <returns></returns>
            protected IList<T> FindPage(string lastObjId, IMongoQuery query, int size, out long totalCount, bool isOutTotalCount, params string[] fields)
            {
                var pQuery = Query.Exists("_id");
    
                if (!string.IsNullOrEmpty(lastObjId))
                {
                    pQuery = Query.And(pQuery, Query.LT("_id", lastObjId));
                }
                pQuery = Query.And(pQuery, query);
                var cursor = Find(size, query, SortBy.Descending("_id"), fields);
                if (isOutTotalCount)
                {
                    totalCount = Count(query);
                }
                else
                {
                    totalCount = 0;
                }
                return cursor.ToList();
            }
            #endregion
            #region 分组
            protected IList<BsonDocument> Group(GroupArgs args)
            {
                return GetCollection().Group(args).ToList();
            }
            #endregion
            #region MapReduce
            protected MapReduceResult MapReduce(MapReduceArgs args)
            {
                return GetCollection().MapReduce(args);
            }
            #endregion
            #region 封装的方法
            /// <summary>
            ///  CreateRegex
            /// </summary>
            /// <param name="reg"></param>
            /// <param name="regOpt"></param>
            /// <returns></returns>
            protected Regex CreateRegex(string reg, RegexOptions regOpt = RegexOptions.IgnoreCase)
            {
                return new Regex(reg, regOpt);
            }
            /// <summary>
            /// 转BsonArray类型
            /// </summary>
            /// <param name="list"></param>
            /// <returns></returns>
            protected BsonArray ToBsonArray(System.Collections.IEnumerable list)
            {
                return new BsonArray(list);
            }
            public IList<BsonDocument> Group(IMongoQuery query, string key, BsonDocument initial, string reduce, string finalize = "")
            {
                return this.GetCollection().Group(query, new BsonJavaScript(key), initial, new BsonJavaScript(reduce), new BsonJavaScript(finalize)).ToList();
            }
            #endregion
            #endregion
      }
    }
  • 相关阅读:
    Git常用命令
    maven profile动态选择配置文件
    Nodejs的偏函数
    用CountDownLatch来同步java的多线程
    NodeJS的Promise的用法
    alluxio常用命令
    常见小代码
    Mongodb
    Mysql_常用语法
    PostgreSQL
  • 原文地址:https://www.cnblogs.com/xishuqingchun/p/4962381.html
Copyright © 2020-2023  润新知