VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • C#教程之C#操作Mongodb

因为MongoDb 跨平台,可以免费使用,读写效率高,集群搭建简单,可以水平扩展等各种因素。

我决定研究一下Mongodb,在查看了相关文档后发现它对C#的支持不错,而且还有现成的C#的驱动,

新版的驱动还支持Linq,因为复杂的查询可以交给Linq去实现。正因为官方的驱动很强大。

刚开始接触时发现在大量的东西要去了解,为了能快速处理简单的项目,我对官方驱动做了进一步封装。项目中需要引入官方提供的dll,下载地址

https://github-cloud.s3.amazonaws.com/releases/699689/ea9bea12-819f-11e6-965b-d3b6bb718019.zip?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAISTNZFOVBIJMK3TQ%2F20161218%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20161218T122012Z&X-Amz-Expires=300&X-Amz-Signature=c52d17292deec2a49eb30f53f4847fc168b82df42dfe69252429faad760e8c05&X-Amz-SignedHeaders=host&actor_id=0&response-content-disposition=attachment%3B%20filename%3DCSharpDriver-2.3.0.zip&response-content-type=application%2Foctet-stream

下载好后解压到相应目录,将里面的dll引入到项目下(如红框所示)

 


以下为我封装的一些简单的增删改查操作

复制代码
  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Threading.Tasks;
  6 using MongoDB.Driver;
  7 using MongoDB.Bson;
  8 using MongoDB.Bson.Serialization.Attributes;
  9 using System.Linq.Expressions;
 10 
 11 namespace Langu.DbHelper
 12 {
 13     /// <summary>
 14     /// MongoDb 数据库操作类
 15     /// </summary>
 16     public class MongoHelper<T> where T : BaseEntity
 17     {
 18         /// <summary>
 19         /// 数据库对象
 20         /// </summary>
 21         private IMongoDatabase database;
 22         /// <summary>
 23         /// 构造函数
 24         /// </summary>
 25         /// <param name="conString">连接字符串</param>
 26         public MongoHelper(String conString)
 27         {
 28             var url = new MongoUrl(conString);
 29             MongoClientSettings mcs = MongoClientSettings.FromUrl(url);
 30             mcs.MaxConnectionLifeTime = TimeSpan.FromMilliseconds(1000);
 31             var client = new MongoClient(mcs);
 32             this.database = client.GetDatabase(url.DatabaseName);
 33         }
 34         /// <summary>
 35         /// 创建集合对象
 36         /// </summary>
 37         /// <param name="collName">集合名称</param>
 38         ///<returns>集合对象</returns>
 39         private IMongoCollection<T> GetColletion(String collName)
 40         {
 41             return database.GetCollection<T>(collName);
 42         }
 43 
 44         #region 增加
 45         /// <summary>
 46         /// 插入对象
 47         /// </summary>
 48         /// <param name="collName">集合名称</param>
 49         /// <param name="t">插入的对象</param>
 50         public void Insert(String collName, T t)
 51         {
 52             var coll = GetColletion(collName);
 53             coll.InsertOne(t);
 54         }
 55         /// <summary>
 56         /// 批量插入
 57         /// </summary>
 58         /// <param name="collName">集合名称</param>
 59         /// <param name="ts">要插入的对象集合</param>
 60         public void InsertBath(String collName, IEnumerable<T> ts)
 61         {
 62             var coll = GetColletion(collName);
 63             coll.InsertMany(ts);
 64         }
 65         #endregion
 66 
 67         #region 删除
 68         /// <summary>
 69         /// 按BsonDocument条件删除
 70         /// </summary>
 71         /// <param name="collName">集合名称</param>
 72         /// <param name="document">文档</param>
 73         /// <returns></returns>
 74         public Int64 Delete(String collName, BsonDocument document)
 75         {
 76             var coll = GetColletion(collName);
 77             var result = coll.DeleteOne(document);
 78             return result.DeletedCount;
 79         }
 80         /// <summary>
 81         /// 按json字符串删除
 82         /// </summary>
 83         /// <param name="collName">集合名称</param>
 84         /// <param name="json">json字符串</param>
 85         /// <returns></returns>
 86         public Int64 Delete(String collName, String json)
 87         {
 88             var coll = GetColletion(collName);
 89             var result = coll.DeleteOne(json);
 90             return result.DeletedCount;
 91         }
 92         /// <summary>
 93         /// 按条件表达式删除
 94         /// </summary>
 95         /// <param name="collName">集合名称</param>
 96         /// <param name="predicate">条件表达式</param>
 97         /// <returns></returns>
 98         public Int64 Delete(String collName, Expression<Func<T, Boolean>> predicate)
 99         {
100             var coll = GetColletion(collName);
101             var result = coll.DeleteOne(predicate);
102             return result.DeletedCount;
103         }
104         /// <summary>
105         /// 按检索条件删除
106         /// 建议用Builders<T>构建复杂的查询条件
107         /// </summary>
108         /// <param name="collName">集合名称</param>
109         /// <param name="filter">条件</param>
110         /// <returns></returns>
111         public Int64 Delete(String collName, FilterDefinition<T> filter)
112         {
113             var coll = GetColletion(collName);
114             var result = coll.DeleteOne(filter);
115             return result.DeletedCount;
116         }
117         #endregion
118 
119         #region 修改
120         /// <summary>
121         /// 修改文档
122         /// </summary>
123         /// <param name="collName">集合名称</param>
124         /// <param name="filter">修改条件</param>
125         /// <param name="update">修改结果</param>
126         /// <param name="upsert">是否插入新文档(filter条件满足就更新,否则插入新文档)</param>
127         /// <returns></returns>
128         public Int64 Update(String collName, Expression<Func<T, Boolean>> filter, UpdateDefinition<T> update, Boolean upsert = false)
129         {
130             var coll = GetColletion(collName);
131             var result = coll.UpdateMany(filter, update, new UpdateOptions { IsUpsert = upsert });
132             return result.ModifiedCount;
133         }
134         /// <summary>
135         /// 用新对象替换新文档
136         /// </summary>
137         /// <param name="collName">集合名称</param>
138         /// <param name="filter">修改条件</param>
139         /// <param name="t">新对象</param>
140         /// <param name="upsert">是否插入新文档(filter条件满足就更新,否则插入新文档)</param>
141         /// <returns>修改影响文档数</returns>
142         public Int64 Update(String collName, Expression<Func<T, Boolean>> filter, T t, Boolean upsert = false)
143         {
144             var coll = GetColletion(collName);
145             BsonDocument document = t.ToBsonDocument<T>();
146             document.Remove("_id");
147             UpdateDocument update = new UpdateDocument("$set", document);
148             var result = coll.UpdateMany(filter, update, new UpdateOptions { IsUpsert = upsert });
149             return result.ModifiedCount;
150         }
151         #endregion
152 
153         /// <summary>
154         /// 查询,复杂查询直接用Linq处理
155         /// </summary>
156         /// <param name="collName">集合名称</param>
157         /// <returns>要查询的对象</returns>
158         public IQueryable<T> GetQueryable(String collName)
159         {
160             var coll = GetColletion(collName);
161             return coll.AsQueryable<T>();
162         }
163         #region 查询 
164         #endregion
165     }
166 
167     /// <summary>
168     /// 实体基类,方便生成_id
169     /// </summary>
170     public class BaseEntity
171     {
172         [BsonRepresentation(BsonType.ObjectId)]
173         public String Id { get; set; }
174         /// <summary>
175         /// 给对象初值
176         /// </summary>
177         public BaseEntity()
178         {
179             this.Id = ObjectId.GenerateNewId().ToString();
180         }
181     }
182 }
复制代码

做了一个简单的控制台调用(前提是mongodb服务已经打开,安装Mongodb以及打开部分有时间会一并发上来)

 

复制代码
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using Langu.DbHelper;
 7 using System.Threading;
 8 using System.Linq.Expressions;
 9 using MongoDB.Driver;
10 
11 namespace Client
12 {
13     class Program
14     {
15         static void Main(string[] args)
16         {
17             //连接字符串 127.0.0.1 服务器IP   27100 mongodb服务端口号   mydb 数据库名称
18             String conString = "mongodb://127.0.0.1:27100/mydb";
19             //实例化MongoHelper对象(泛型版本),构造函数要求传入连接字符串
20             MongoHelper<User> mongoHelper = new MongoHelper<User>(conString);
21             //查询集合 user中有多少数据量
22             var cnt = mongoHelper.GetQueryable("user").Count();
23             Console.WriteLine(cnt);
24             Console.ReadKey();
25         }
26     }
27 
28     internal class User : BaseEntity
29     {
30         public int Age { get; set; }
31         public String Name { get; set; }
32     }
33 }
复制代码

 

-----------------------------唯有自身强大,才能不惧外物。 http://www.cnblogs.com/lclblog/

相关教程