程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#操作Mongodb,

C#操作Mongodb,

編輯: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 }

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved