隨着NoSQL的應用越來越廣泛,很多面試都需要熟悉了解NoSQL【如:Redis,MongoDB等】,本文以一個簡單的小例子,簡述如何通過C#來操作MongoDB,進行數據的讀寫操作,僅供學習分享使用,如有不足之處,還請指正。
涉及知識點
- MongoDB的基礎知識,CRUD(增刪改查)等【關於MongoDB的基礎知識,如果不太了解的,可參考前面幾篇博文】。
- C#面向對象基礎知識,WinForm基礎編程。
MongoDB驅動安裝
項目--右鍵--管理Nuget程序包--打卡Nuget包管理器--瀏覽搜索MongoDB.Driver--安裝。如下所示:
示例截圖
示例雖小,實現了查詢,條件查詢,明細顯示,新增等功能,如下所示:
新增功能
C#操作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 MongoDB.Driver; 7 using MongoDB.Bson; 8 using MongoDB.Bson.Serialization; 9 using System.Web.Script.Serialization; 10 11 namespace DemoMongo.Common 12 { 13 /// <summary> 14 /// Mongo幫助類 15 /// </summary> 16 public class MongoHelper<T> 17 { 18 private string connStr = "";//服務器網址 19 20 private string dbName = "";//數據庫名稱 21 22 private IMongoClient client;//連接客戶端 23 24 private IMongoDatabase db;//連接數據庫 25 26 private string collName ;//集合名稱 27 28 public MongoHelper() { 29 30 } 31 32 public MongoHelper(string connStr,string dbName,string collName) { 33 this.connStr = connStr; 34 this.dbName = dbName; 35 this.collName = collName; 36 this.Init(); 37 } 38 39 /// <summary> 40 /// 初始化連接客戶端 41 /// </summary> 42 private void Init() 43 { 44 if (client == null) 45 { 46 client = new MongoClient(this.connStr); 47 } 48 if (db == null) { 49 db = client.GetDatabase(this.dbName); 50 } 51 } 52 53 /// <summary> 54 /// 插入對象 55 /// </summary> 56 /// <typeparam name="T"></typeparam> 57 /// <param name="obj"></param> 58 public void Insert(T obj) 59 { 60 IMongoCollection<T> collention = db.GetCollection<T>(collName); 61 collention.InsertOneAsync(obj); 62 } 63 64 /// <summary> 65 /// 字典形式插入 66 /// </summary> 67 /// <param name="dicInfo"></param> 68 public void Insert(Dictionary<string,string> dicInfo) 69 { 70 var collection = db.GetCollection<BsonDocument>(collName); 71 var document = new BsonDocument(dicInfo); 72 collection.InsertOne(document); 73 } 74 75 /// <summary> 76 /// 無條件查詢,即返回全部 77 /// </summary> 78 /// <returns></returns> 79 public List<T> Query() { 80 var collection = db.GetCollection<BsonDocument>(collName); 81 var rest = collection.Find(Builders<BsonDocument>.Filter.Empty); 82 return rest.As<T>().ToList(); 83 } 84 85 /// <summary> 86 /// 按名稱進行查詢 87 /// </summary> 88 /// <param name="name"></param> 89 /// <returns></returns> 90 public List<T> Query(object name) { 91 var collection = db.GetCollection<T>(collName); 92 var rest = collection.Find(Builders<T>.Filter.Eq("name",name)); 93 return rest.As<T>().ToList(); 94 } 95 96 97 /// <summary> 98 /// 只查詢一條 99 /// </summary> 100 /// <param name="Id"></param> 101 /// <returns></returns> 102 public string QueryOne(string Id) { 103 var collection = db.GetCollection<T>(collName); 104 var rest = collection.Find(Builders<T>.Filter.Eq("Id",new ObjectId(Id))).Limit(1); 105 106 T t = rest.As<T>().ToList()[0]; 107 JavaScriptSerializer jserializer = new JavaScriptSerializer(); 108 string strJson = jserializer.Serialize(t); 109 return strJson; 110 } 111 } 112 }
代碼調用
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Configuration; 5 using System.Data; 6 using System.Drawing; 7 using System.IO; 8 using System.Linq; 9 using System.Text; 10 using System.Threading.Tasks; 11 using System.Windows.Forms; 12 using DemoMongo.Common; 13 14 namespace DemoMongo 15 { 16 public partial class FrmMain : Form 17 { 18 private MongoHelper<Student> helper; 19 20 public FrmMain() 21 { 22 InitializeComponent(); 23 string connStr = ConfigurationManager.AppSettings["connStr"]; 24 string dbName = ConfigurationManager.AppSettings["dbName"]; 25 string collName = "student"; 26 helper = new MongoHelper<Student>(connStr,dbName,collName); 27 28 } 29 30 private void FrmMain_Load(object sender, EventArgs e) 31 { 32 List<Student> list = helper.Query(); 33 this.dgView.AutoGenerateColumns = false; 34 this.bsView.DataSource = list; 35 this.dgView.DataSource = bsView; 36 } 37 38 private void btnQuery_Click(object sender, EventArgs e) 39 { 40 string name = this.txtName.Text.Trim(); 41 42 List<Student> list = new List<Student>(); 43 if (string.IsNullOrEmpty(name)) 44 { 45 list = helper.Query(); 46 } 47 else { 48 //注意:此處姓名在MongoDB中存儲的數據類型不是固定的,可能是字符串也可能是整數,所以需要判斷,否則查詢不出來 49 int name1 = 0; 50 if (int.TryParse(name, out name1)) 51 { 52 list = helper.Query(name1); 53 } 54 else { 55 list = helper.Query(name); 56 } 57 58 } 59 this.dgView.AutoGenerateColumns = false; 60 this.bsView.DataSource = list; 61 this.dgView.DataSource = bsView; 62 } 63 64 private void btnAdd_Click(object sender, EventArgs e) 65 { 66 FrmAdd add = new FrmAdd(this.helper); 67 add.ShowDialog(); 68 btnQuery_Click(sender, e); 69 } 70 71 private void dgView_CellClick(object sender, DataGridViewCellEventArgs e) 72 { 73 //只有當第0列被點擊時才生效 74 if (e.ColumnIndex == 0) 75 { 76 string id = ((Student)dgView.CurrentRow.DataBoundItem).Id.ToString(); 77 string student = helper.QueryOne(id); 78 this.txtContent.Text = JsonHelper.ConvertJsonString(student); 79 } 80 } 81 82 } 83 }
以上就是C#對於MongoDB的基礎操作,旨在拋磚引玉,共同進步。
備注
踏莎行·候館梅殘
【作者】歐陽修
候館梅殘,溪橋柳細。草薰風暖搖征轡。離愁漸遠漸無窮,迢迢不斷如春水。
寸寸柔腸,盈盈粉淚。樓高莫近危闌倚。平蕪盡處是春山,行人更在春山外。