基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)

本文涉及的产品
云数据库 MongoDB,独享型 2核8GB
推荐场景:
构建全方位客户视图
简介:

近期工作中有使用到 MongoDb作为日志持久化对象,需要实现对MongoDb的增、删、改、查,但由于MongoDb的版本比较新,是2.4以上版本的,网上已有的一些MongoDb Helper类都是基于之前MongoDb旧的版本,无法适用于新版本的MongoDb,故我基于MongoDb官方C#驱动重新封装了MongoDbCsharpHelper类(CRUD类),完整代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
using  MongoDB;
using  MongoDB.Bson;
using  MongoDB.Driver;
using  System;
using  System.Collections;
using  System.Collections.Generic;
using  System.Linq;
using  System.Linq.Expressions;
using  System.Reflection;
using  System.Threading;
using  System.Web;
 
namespace  Zuowj.Utils
{
     /// <summary>
     /// MongoDbCsharpHelper:MongoDb基于C#语言操作帮助类
     /// Author:Zuowenjun
     /// Date:2017/11/16
     /// </summary>
     public  class  MongoDbCsharpHelper
     {
         private  readonly  string  connectionString =  null ;
         private  readonly  string  databaseName =  null ;
         private  MongoDB.Driver.IMongoDatabase database =  null ;
         private  readonly  bool  autoCreateDb =  false ;
         private  readonly  bool  autoCreateCollection =  false ;
 
         static  MongoDbCsharpHelper()
         {
             BsonDefaults.GuidRepresentation = GuidRepresentation.Standard;
         }
 
         public  MongoDbCsharpHelper( string  mongoConnStr,  string  dbName,  bool  autoCreateDb =  false bool  autoCreateCollection =  false )
         {
             this .connectionString = mongoConnStr;
             this .databaseName = dbName;
             this .autoCreateDb = autoCreateDb;
             this .autoCreateCollection = autoCreateCollection;
         }
 
         #region 私有方法
 
         private  MongoClient CreateMongoClient()
         {
             return  new  MongoClient(connectionString);
         }
 
 
         private  MongoDB.Driver.IMongoDatabase GetMongoDatabase()
         {
             if  (database ==  null )
             {
                 var  client = CreateMongoClient();
                 if  (!DatabaseExists(client, databaseName) && !autoCreateDb)
                 {
                     throw  new  KeyNotFoundException( "此MongoDB名称不存在:"  + databaseName);
                 }
 
                 database = CreateMongoClient().GetDatabase(databaseName);
             }
 
             return  database;
         }
 
         private  bool  DatabaseExists(MongoClient client,  string  dbName)
         {
             try
             {
                 var  dbNames = client.ListDatabases().ToList().Select(db => db.GetValue( "name" ).AsString);
                 return  dbNames.Contains(dbName);
             }
             catch  //如果连接的账号不能枚举出所有DB会报错,则默认为true
             {
                 return  true ;
             }
 
         }
 
         private  bool  CollectionExists(IMongoDatabase database,  string  collectionName)
         {
             var  options =  new  ListCollectionsOptions
             {
                 Filter = Builders<BsonDocument>.Filter.Eq( "name" , collectionName)
             };
 
             return  database.ListCollections(options).ToEnumerable().Any();
         }
 
 
         private  MongoDB.Driver.IMongoCollection<TDoc> GetMongoCollection<TDoc>( string  name, MongoCollectionSettings settings =  null )
         {
             var  mongoDatabase = GetMongoDatabase();
 
             if  (!CollectionExists(mongoDatabase, name) && !autoCreateCollection)
             {
                 throw  new  KeyNotFoundException( "此Collection名称不存在:"  + name);
             }
 
             return  mongoDatabase.GetCollection<TDoc>(name, settings);
         }
 
         private  List<UpdateDefinition<TDoc>> BuildUpdateDefinition<TDoc>( object  doc,  string  parent)
         {
             var  updateList =  new  List<UpdateDefinition<TDoc>>();
             foreach  ( var  property  in  typeof (TDoc).GetProperties(BindingFlags.Instance | BindingFlags.Public))
             {
                 var  key = parent ==  null  ? property.Name :  string .Format( "{0}.{1}" , parent, property.Name);
                 //非空的复杂类型
                 if  ((property.PropertyType.IsClass || property.PropertyType.IsInterface) && property.PropertyType !=  typeof ( string ) && property.GetValue(doc) !=  null )
                 {
                     if  ( typeof (IList).IsAssignableFrom(property.PropertyType))
                     {
                         #region 集合类型
                         int  i = 0;
                         var  subObj = property.GetValue(doc);
                         foreach  ( var  item  in  subObj  as  IList)
                         {
                             if  (item.GetType().IsClass || item.GetType().IsInterface)
                             {
                                 updateList.AddRange(BuildUpdateDefinition<TDoc>(doc,  string .Format( "{0}.{1}" , key, i)));
                             }
                             else
                             {
                                 updateList.Add(Builders<TDoc>.Update.Set( string .Format( "{0}.{1}" , key, i), item));
                             }
                             i++;
                         }
                         #endregion
                     }
                     else
                     {
                         #region 实体类型
                         //复杂类型,导航属性,类对象和集合对象
                         var  subObj = property.GetValue(doc);
                         foreach  ( var  sub  in  property.PropertyType.GetProperties(BindingFlags.Instance | BindingFlags.Public))
                         {
                             updateList.Add(Builders<TDoc>.Update.Set( string .Format( "{0}.{1}" , key, sub.Name), sub.GetValue(subObj)));
                         }
                         #endregion
                     }
                 }
                 else  //简单类型
                 {
                     updateList.Add(Builders<TDoc>.Update.Set(key, property.GetValue(doc)));
                 }
             }
 
             return  updateList;
         }
 
 
         private  void  CreateIndex<TDoc>(IMongoCollection<TDoc> col,  string [] indexFields, CreateIndexOptions options =  null )
         {
             if  (indexFields ==  null )
             {
                 return ;
             }
             var  indexKeys = Builders<TDoc>.IndexKeys;
             IndexKeysDefinition<TDoc> keys =  null ;
             if  (indexFields.Length > 0)
             {
                 keys = indexKeys.Descending(indexFields[0]);
             }
             for  ( var  i = 1; i < indexFields.Length; i++)
             {
                 var  strIndex = indexFields[i];
                 keys = keys.Descending(strIndex);
             }
 
             if  (keys !=  null )
             {
                 col.Indexes.CreateOne(keys, options);
             }
 
         }
 
         #endregion
 
         public  void  CreateCollectionIndex<TDoc>( string  collectionName,  string [] indexFields, CreateIndexOptions options =  null )
         {
             CreateIndex(GetMongoCollection<TDoc>(collectionName), indexFields, options);
         }
 
         public  void  CreateCollection<TDoc>( string [] indexFields =  null , CreateIndexOptions options =  null )
         {
             string  collectionName =  typeof (TDoc).Name;
             CreateCollection<TDoc>(collectionName, indexFields, options);
         }
 
         public  void  CreateCollection<TDoc>( string  collectionName,  string [] indexFields =  null , CreateIndexOptions options =  null )
         {
             var  mongoDatabase = GetMongoDatabase();
             mongoDatabase.CreateCollection(collectionName);
             CreateIndex(GetMongoCollection<TDoc>(collectionName), indexFields, options);
         }
 
 
         public  List<TDoc> Find<TDoc>(Expression<Func<TDoc,  bool >> filter, FindOptions options =  null )
         {
             string  collectionName =  typeof (TDoc).Name;
             return  Find<TDoc>(collectionName, filter, options);
         }
 
         public  List<TDoc> Find<TDoc>( string  collectionName, Expression<Func<TDoc,  bool >> filter, FindOptions options =  null )
         {
             var  colleciton = GetMongoCollection<TDoc>(collectionName);
             return  colleciton.Find(filter, options).ToList();
         }
 
 
         public  List<TDoc> FindByPage<TDoc, TResult>(Expression<Func<TDoc,  bool >> filter, Expression<Func<TDoc, TResult>> keySelector,  int  pageIndex,  int  pageSize,  out  int  rsCount)
         {
             string  collectionName =  typeof (TDoc).Name;
             return  FindByPage<TDoc, TResult>(collectionName, filter, keySelector, pageIndex, pageSize,  out  rsCount);
         }
 
         public  List<TDoc> FindByPage<TDoc, TResult>( string  collectionName, Expression<Func<TDoc,  bool >> filter, Expression<Func<TDoc, TResult>> keySelector,  int  pageIndex,  int  pageSize,  out  int  rsCount)
         {
             var  colleciton = GetMongoCollection<TDoc>(collectionName);
             rsCount = colleciton.AsQueryable().Where(filter).Count();
 
             int  pageCount = rsCount / pageSize + ((rsCount % pageSize) > 0 ? 1 : 0);
             if  (pageIndex > pageCount) pageIndex = pageCount;
             if  (pageIndex <= 0) pageIndex = 1;
 
             return  colleciton.AsQueryable( new  AggregateOptions { AllowDiskUse =  true  }).Where(filter).OrderByDescending(keySelector).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
         }
 
         public  void  Insert<TDoc>(TDoc doc, InsertOneOptions options =  null )
         {
             string  collectionName =  typeof (TDoc).Name;
             Insert<TDoc>(collectionName, doc, options);
         }
 
         public  void  Insert<TDoc>( string  collectionName, TDoc doc, InsertOneOptions options =  null )
         {
             var  colleciton = GetMongoCollection<TDoc>(collectionName);
             colleciton.InsertOne(doc, options);
         }
 
 
         public  void  InsertMany<TDoc>(IEnumerable<TDoc> docs, InsertManyOptions options =  null )
         {
             string  collectionName =  typeof (TDoc).Name;
             InsertMany<TDoc>(collectionName, docs, options);
         }
 
         public  void  InsertMany<TDoc>( string  collectionName, IEnumerable<TDoc> docs, InsertManyOptions options =  null )
         {
             var  colleciton = GetMongoCollection<TDoc>(collectionName);
             colleciton.InsertMany(docs, options);
         }
 
         public  void  Update<TDoc>(TDoc doc, Expression<Func<TDoc,  bool >> filter, UpdateOptions options =  null )
         {
             string  collectionName =  typeof (TDoc).Name;
             var  colleciton = GetMongoCollection<TDoc>(collectionName);
             List<UpdateDefinition<TDoc>> updateList = BuildUpdateDefinition<TDoc>(doc,  null );
             colleciton.UpdateOne(filter, Builders<TDoc>.Update.Combine(updateList), options);
         }
 
         public  void  Update<TDoc>( string  collectionName, TDoc doc, Expression<Func<TDoc,  bool >> filter, UpdateOptions options =  null )
         {
             var  colleciton = GetMongoCollection<TDoc>(collectionName);
             List<UpdateDefinition<TDoc>> updateList = BuildUpdateDefinition<TDoc>(doc,  null );
             colleciton.UpdateOne(filter, Builders<TDoc>.Update.Combine(updateList), options);
         }
 
 
         public  void  Update<TDoc>(TDoc doc, Expression<Func<TDoc,  bool >> filter, UpdateDefinition<TDoc> updateFields, UpdateOptions options =  null )
         {
             string  collectionName =  typeof (TDoc).Name;
             Update<TDoc>(collectionName, doc, filter, updateFields, options);
         }
 
         public  void  Update<TDoc>( string  collectionName, TDoc doc, Expression<Func<TDoc,  bool >> filter, UpdateDefinition<TDoc> updateFields, UpdateOptions options =  null )
         {
             var  colleciton = GetMongoCollection<TDoc>(collectionName);
             colleciton.UpdateOne(filter, updateFields, options);
         }
 
 
         public  void  UpdateMany<TDoc>(TDoc doc, Expression<Func<TDoc,  bool >> filter, UpdateOptions options =  null )
         {
             string  collectionName =  typeof (TDoc).Name;
             UpdateMany<TDoc>(collectionName, doc, filter, options);
         }
 
 
         public  void  UpdateMany<TDoc>( string  collectionName, TDoc doc, Expression<Func<TDoc,  bool >> filter, UpdateOptions options =  null )
         {
             var  colleciton = GetMongoCollection<TDoc>(collectionName);
             List<UpdateDefinition<TDoc>> updateList = BuildUpdateDefinition<TDoc>(doc,  null );
             colleciton.UpdateMany(filter, Builders<TDoc>.Update.Combine(updateList), options);
         }
 
 
         public  void  Delete<TDoc>(Expression<Func<TDoc,  bool >> filter, DeleteOptions options =  null )
         {
             string  collectionName =  typeof (TDoc).Name;
             Delete<TDoc>(collectionName, filter, options);
         }
 
         public  void  Delete<TDoc>( string  collectionName, Expression<Func<TDoc,  bool >> filter, DeleteOptions options =  null )
         {
             var  colleciton = GetMongoCollection<TDoc>(collectionName);
             colleciton.DeleteOne(filter, options);
         }
 
 
         public  void  DeleteMany<TDoc>(Expression<Func<TDoc,  bool >> filter, DeleteOptions options =  null )
         {
             string  collectionName =  typeof (TDoc).Name;
             DeleteMany<TDoc>(collectionName, filter, options);
         }
 
 
         public  void  DeleteMany<TDoc>( string  collectionName, Expression<Func<TDoc,  bool >> filter, DeleteOptions options =  null )
         {
             var  colleciton = GetMongoCollection<TDoc>(collectionName);
             colleciton.DeleteMany(filter, options);
         }
 
         public  void  ClearCollection<TDoc>( string  collectionName)
         {
             var  colleciton = GetMongoCollection<TDoc>(collectionName);
             var  inddexs = colleciton.Indexes.List();
             List<IEnumerable<BsonDocument>> docIndexs =  new  List<IEnumerable<BsonDocument>>();
             while  (inddexs.MoveNext())
             {
                 docIndexs.Add(inddexs.Current);
             }
             var  mongoDatabase = GetMongoDatabase();
             mongoDatabase.DropCollection(collectionName);
 
             if  (!CollectionExists(mongoDatabase, collectionName))
             {
                 CreateCollection<TDoc>(collectionName);
             }
 
             if  (docIndexs.Count > 0)
             {
                 colleciton = mongoDatabase.GetCollection<TDoc>(collectionName);
                 foreach  ( var  index  in  docIndexs)
                 {
                     foreach  (IndexKeysDefinition<TDoc> indexItem  in  index)
                     {
                         try
                         {
                             colleciton.Indexes.CreateOne(indexItem);
                         }
                         catch
                         { }
                     }
                 }
             }
 
         }
     }
}

对上述代码中几个特别的点进行简要说明:

1.由于MongoClient.GetDatabase 获取DB、MongoClient.GetCollection<TDoc> 获取文档(也可称为表)的方法 都有一个特点,即:如果指定的DB名称、Collection名称不存在,则会直接创建,但有的时候可能是因为DB名称、Collection名称写错了导致误创建了的DB或Collection,那就引起不必要的麻烦,故在MongoDbCsharpHelper类类内部封装了两个私有的方法:DatabaseExists(判断DB是否存在,如是连接的账号没有检索DB的权限可能会报错,故代码中加了直接返回true)、CollectionExists(判断Collection是否存在);

2.每个CRUD方法,我都分别重载了两个方法,一个是无需指定Collection名称,一个是需要指定Collection名称,为什么这么做呢?原因很简单,因为有时Collection的结构是相同的但又是不同的Collection,这时TDoc是同一个实体类,但collectionName却是不同的;

3.分页查询的时候如果Collection的数据量比较大,那么就会报类似错误:exception: Sort exceeded memory limit of 104857600 bytes, but did not opt in to external sorting. Aborting operation. Pass allowDiskUse:true,根据报错提示,我们在查询大数据量时增加AggregateOptions对象,如: colleciton.AsQueryable(new AggregateOptions { AllowDiskUse = true })

4.ClearCollection清除Collection的所有数据,如果Collection的数据量非常大,那么直接使用colleciton.DeleteMany可能需要很久,有没有类似SQL SERVER 的truncate table的方法呢?经过多方论证,很遗憾并没有找到同类功能的方法,只有DropCollection方法,而这个DropCollection方法是直接删除Collection,当然包括Collection的所有数据,效率也非常高,但是由于是Drop,Collection就不存在了,如果再访问有可能会报Collection不存在的错误,那有没有好的办法解决了,当然有,那就是先DropCollection 然后再CreateCollection,最后别忘了把原有的索引插入到新创建的Collection中,这样就实现了truncate 初始化表的作用,当然在创建索引的时候,有的时候可能报报错(如:_id),因为_id默认就会被创建索引,再创建可能就会报错,故colleciton.Indexes.CreateOne外我加了try catch,如果报错则忽略。

5.CreateCollection(创建集合)、CreateCollectionIndex(创建集合索引)因为有的时候我们需要明确的去创建一个Collection或对已有的Collection创建索引,如果通过shell命令会非常不方便,故在此封装了一下。

 使用示例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var  mongoDbHelper =  new  MongoDbCsharpHelper( "MongoDbConnectionString" "LogDB" );
 
mongoDbHelper.CreateCollection<SysLogInfo>( "SysLog1" , new []{ "LogDT" });
 
mongoDbHelper.Find<SysLogInfo>( "SysLog1" , t => t.Level ==  "Info" );
 
int  rsCount=0;
mongoDbHelper.FindByPage<SysLogInfo, SysLogInfo>( "SysLog1" ,t=>t.Level== "Info" ,t=>t,1,20, out  rsCount);
 
mongoDbHelper.Insert<SysLogInfo>( "SysLog1" , new  SysLogInfo { LogDT = DateTime.Now, Level =  "Info" , Msg =  "测试消息"  });
 
mongoDbHelper.Update<SysLogInfo>( "SysLog1" , new  SysLogInfo { LogDT = DateTime.Now, Level =  "Error" , Msg =  "测试消息2"  },t => t.LogDT== new  DateTime(1900,1,1));
 
mongoDbHelper.Delete<SysLogInfo>(t => t.Level ==  "Info" );
 
mongoDbHelper.ClearCollection<SysLogInfo>( "SysLog1" );

 

本文转自 梦在旅途 博客园博客,原文链接: http://www.cnblogs.com/zuowj/p/8242532.html ,如需转载请自行联系原作者

相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。 &nbsp; 相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
相关文章
|
7天前
|
存储 C# 索引
C# 一分钟浅谈:数组与集合类的基本操作
【9月更文挑战第1天】本文详细介绍了C#中数组和集合类的基本操作,包括创建、访问、遍历及常见问题的解决方法。数组适用于固定长度的数据存储,而集合类如`List<T>`则提供了动态扩展的能力。文章通过示例代码展示了如何处理索引越界、数组长度不可变及集合容量不足等问题,并提供了解决方案。掌握这些基础知识可使程序更加高效和清晰。
30 2
|
6天前
|
C# 数据安全/隐私保护
C# 一分钟浅谈:类与对象的概念理解
【9月更文挑战第2天】本文从零开始详细介绍了C#中的类与对象概念。类作为一种自定义数据类型,定义了对象的属性和方法;对象则是类的实例,拥有独立的状态。通过具体代码示例,如定义 `Person` 类及其实例化过程,帮助读者更好地理解和应用这两个核心概念。此外,还总结了常见的问题及解决方法,为编写高质量的面向对象程序奠定基础。
11 2
|
1月前
|
C#
C#中的类和继承
C#中的类和继承
30 6
|
19天前
|
Java C# 索引
C# 面向对象编程(一)——类
C# 面向对象编程(一)——类
25 0
|
23天前
|
开发框架 .NET 编译器
C# 中的记录(record)类型和类(class)类型对比总结
C# 中的记录(record)类型和类(class)类型对比总结
|
3月前
|
开发框架 .NET 编译器
程序与技术分享:C#基础知识梳理系列三:C#类成员:常量、字段、属性
程序与技术分享:C#基础知识梳理系列三:C#类成员:常量、字段、属性
23 2
|
3月前
|
C#
C# 版本的 计时器类 精确到微秒 秒后保留一位小数 支持年月日时分秒带单位的输出
这篇2010年的文章是从别处搬运过来的,主要包含一个C#类`TimeCount`,该类有多个方法用于处理时间相关的计算。例如,`GetMaxYearCount`计算以毫秒为单位的最大年数,`GetCurrentTimeByMiliSec`将当前时间转换为毫秒,还有`SecondsToYYMMDDhhmmss`将秒数转换为年月日时分秒的字符串。此外,类中还包括一些辅助方法,如处理小数点后保留一位数字的`RemainOneFigureAfterDot`。
|
3月前
|
存储 安全 C#
C# 类的深入指南
C# 类的深入指南
|
4月前
|
C#
C#的类和对象的概念学习案例刨析
【5月更文挑战第17天】C#是一种面向对象的语言,以类和对象为核心。类作为对象的模板,定义了属性(如Name, Age)和行为(如Greet)。对象是类的实例,可设置属性值。封装通过访问修饰符隐藏实现细节,如Customer类的私有name字段通过Name属性访问。继承允许新类(如Employee)从现有类(Person)继承并扩展。多态让不同对象(如Circle, Square)共享相同接口(Shape),实现抽象方法Area,提供灵活的代码设计。
61 1
|
4月前
|
C#
c# 所有类的最终基类:Object
c# 所有类的最终基类:Object
33 0
下一篇
DDNS