zoukankan      html  css  js  c++  java
  • C#封装MongoDB工具类库

    什么是MongoDB

    MongoDB 是由C++语言编写的,是一个基于分布式文件存储的开源数据库系统。 在高负载的情况下,添加更多的节点,可以保证服务器性能。 MongoDB 旨在为WEB应用提供可扩展的高性能数据存储解决方案。 MongoDB 将数据存储为一个文档,数据结构由键值(key=>value)对组成。MongoDB 文档类似于 JSON 对象。字段值可以包含其他文档,数组及文档数组。

    MongoDB安装

      园内很多教程,比较详细的在这里

    工具类说明

    1、基于MongoDB.Driver封装MongoDB的一些基本操作

    2、利用反射每个实体类名作为存储数据的表名

    3、数据ID自增使用MongoDB自带的ObjectID

    MongoDB连接类

    //实例化对象 类名保存为MongoDB表名称
    MongoDBUtil<PlayerEntity> mgdbUtil = new MongoDBUtil<PlayerEntity>();
    //清空数据
    mgdbUtil.DeleteAll();
    //插入一条数据
    PlayerEntity t = new PlayerEntity() { NId = 1, Name = "曾城", Birthday = DateTime.Parse("1900-1-1"), CountryName = "中国", Club = "广州恒大", Position = "GK" };
    mgdbUtil.Insert(t);
    //更新一条数据
    PlayerEntity t2 = new PlayerEntity() { NId = 1, Name = "曾城update", Birthday = DateTime.Now, CountryName = "中国", Club = "广州恒大", Position = "GK" };
    mgdbUtil.Update(t2, s => s.NId == 1);
    //查询一条数据
    var m = mgdbUtil.GetEntity(s => s.NId == 1);
    Console.WriteLine(JsonUtil.Serialize(m));
    //删除一条数据
    mgdbUtil.Delete(s => s.NId == 1);

    MongoDBUtil连接类

     1 public class MongoDB
     2     {
     3         private static string connStr = ConfigUtil.GetValue(SysConstant._MongoDBConnection);
     4 
     5         private static string dbName = ConfigUtil.GetValue(SysConstant._MongoDB);
     6 
     7         private static IMongoDatabase db = null;
     8 
     9         private static readonly object lockHelper = new object();
    10 
    11         private MongoDB()
    12         {
    13         }
    14 
    15         /// <summary>
    16         /// 创建DB
    17         /// </summary>
    18         /// <returns></returns>
    19         public static IMongoDatabase CreateDB()
    20         {
    21             if (db == null)
    22             {
    23                 lock (lockHelper)
    24                 {
    25                     if (db == null)
    26                     {
    27                         var client = new MongoClient(connStr);
    28                         db = client.GetDatabase(dbName);
    29                     }
    30                 }
    31             }
    32             return db;
    33         }
    34     }

    MongoDBUtil数据操作类

      1 public class MongoDBUtil<T> where T : BaseEntity
      2     {
      3         private IMongoDatabase db = null;
      4         private IMongoCollection<T> collection = null;
      5 
      6         public MongoDBUtil()
      7         {
      8             this.db = MongoDB.CreateDB();
      9             collection = db.GetCollection<T>(typeof(T).Name);
     10         }
     11 
     12         /// <summary>
     13         /// 添加一条对象记录
     14         /// </summary>
     15         /// <param name="entity"></param>
     16         /// <returns></returns>
     17         public T Insert(T entity)
     18         {
     19             entity.Id = ObjectId.GenerateNewId();
     20             collection.InsertOne(entity);
     21             return entity;
     22         }
     23 
     24         /// <summary>
     25         /// 根据ID更新一条记录  
     26         /// </summary>
     27         /// <param name="id"></param>
     28         /// <param name="field"></param>
     29         /// <param name="value"></param>
     30         public void Update(string id, string field, string value)
     31         {
     32             var filter = Builders<T>.Filter.Eq("Id", id);
     33             var updated = Builders<T>.Update.Set(field, value);
     34             UpdateResult result = collection.UpdateOneAsync(filter, updated).Result;
     35         }
     36 
     37         /// <summary>
     38         /// 根据ID更新一条记录
     39         /// </summary>
     40         /// <param name="entity"></param>
     41         /// <param name="id"></param>
     42         public void Update(T entity, string id)
     43         {
     44             Update(entity, a => a.Id == ObjectId.Parse(id));
     45         }
     46 
     47         /// <summary>
     48         /// 根据条件更新一条记录
     49         /// </summary>
     50         /// <param name="entity"></param>
     51         /// <param name="func"></param>
     52         public void Update(T entity, Expression<Func<T, bool>> func)
     53         {
     54             var old = GetEntity(func);
     55             foreach (var prop in entity.GetType().GetProperties())
     56             {
     57                 if (prop.Name.Equals("Id"))
     58                     continue;
     59                 var newValue = prop.GetValue(entity);
     60                 var oldValue = old.GetType().GetProperty(prop.Name).GetValue(old);
     61                 if (newValue != null)
     62                 {
     63                     if (!newValue.ToString().Equals(oldValue.ToString()))
     64                     {
     65                         old.GetType().GetProperty(prop.Name).SetValue(old, newValue);
     66                     }
     67                 }
     68             }
     69             collection.ReplaceOne(func, old);
     70         }
     71 
     72         /// <summary>
     73         /// 根据ID获取对象
     74         /// </summary>
     75         /// <param name="id"></param>
     76         /// <returns></returns>
     77         public T GetEntity(string id)
     78         {
     79             return collection.Find(a => a.Id == ObjectId.Parse(id)).ToList().FirstOrDefault();
     80         }
     81 
     82         /// <summary>
     83         /// Lambar 表达式选择一个模型
     84         /// </summary>
     85         /// <param name="func"></param>
     86         /// <returns></returns>
     87         public T GetEntity(Expression<Func<T, bool>> func)
     88         {
     89             return collection.Find(func).ToList().FirstOrDefault();
     90         }
     91 
     92         /// <summary>
     93         /// 获取全部信息
     94         /// </summary>
     95         /// <returns></returns>
     96         public List<T> ListAll()
     97         {
     98             return ListByCondition(s => 1 == 1);
     99         }
    100 
    101         /// <summary>
    102         /// 根据条件筛选列表
    103         /// </summary>
    104         /// <param name="func"></param>
    105         /// <returns></returns>
    106         public List<T> ListByCondition(Expression<Func<T, bool>> func)
    107         {
    108             return collection.Find(func).ToList<T>();
    109         }
    110 
    111         /// <summary>
    112         /// 获取列表
    113         /// </summary>
    114         /// <param name="func"></param>
    115         /// <param name="count">数量</param>
    116         /// <returns></returns>
    117         public List<T> ListByCondition(Expression<Func<T, bool>> func, int count)
    118         {
    119             return collection.Find(func).Limit(count).ToList();
    120         }
    121 
    122         /// <summary>
    123         /// 获取分页列表
    124         /// </summary>
    125         /// <param name="func"></param>
    126         /// <param name="page"></param>
    127         /// <param name="pageSize"></param>
    128         /// <param name="record"></param>
    129         /// <param name="sort"></param>
    130         /// <returns></returns>
    131         public List<T> ListPage(Expression<Func<T, bool>> func, int page, int pageSize, ref long record, SortDefinition<T> sort = null)
    132         {
    133             record = collection.Count(func);
    134             return collection.Find(func).Sort(sort).Skip((page - 1) * pageSize).Limit(pageSize).ToList();
    135         }
    136 
    137         /// <summary>
    138         /// 删除数据
    139         /// </summary>
    140         /// <param name="func"></param>
    141         /// <returns></returns>
    142         public long Delete(Expression<Func<T, bool>> func)
    143         {
    144             return collection.DeleteMany(func).DeletedCount;
    145         }
    146 
    147         /// <summary>
    148         /// 删除全部
    149         /// </summary>
    150         /// <returns></returns>
    151         public long DeleteAll()
    152         {
    153             return Delete(s => 1 == 1);
    154         }
    155     }

    问题:

    目前数据Id自增采用MongoDB默认ObjectId,暂未实现自定义自增解决方案

    MongoDB 日期类型保存为UTC格式,
    例:本地时间(8时区)2017-03-30 15:00:00 MongoDB保存为(格林尼治时间):ISODate("2017-03-30T07:00:00.000Z")
    相差8小时

    测试结果:

    MongoDB测试结果

    Github开源地址:https://github.com/willianchen/CML.MongoDB

    欢迎各位园友测试与拍砖,基于上面的问题希望大家各抒己见,提供一些解决方案。

  • 相关阅读:
    洛谷.1110.[ZJOI2007]报表统计(Multiset Heap)
    洛谷.1110.[ZJOI2007]报表统计(Multiset)
    洛谷.3809.[模板]后缀排序(后缀数组 倍增) & 学习笔记
    洛谷.2801.教主的魔法(分块 二分)
    洛谷.2709.小B的询问(莫队)
    COGS.1901.[模板][国家集训队2011]数颜色(带修改莫队)
    COGS.1822.[AHOI2013]作业(莫队 树状数组/分块)
    COGS.1689.[HNOI2010]Bounce 弹飞绵羊(分块)
    COGS.264.数列操作(分块 单点加 区间求和)
    COGS.1317.数列操作c(分块 区间加 区间求和)
  • 原文地址:https://www.cnblogs.com/chenminli/p/6646703.html
Copyright © 2011-2022 走看看