一、MongoClient類
在2.10.0版本中引入了MongoClient類,同時在其API中也說明了Mongo類會在將來的版本中被MongoClient替換(Note: This class has been superseded by MongoClient
, and may be deprecated in a future release.)。故在這次調整中,也對原先的Mongodb部分做了相應的修改。
設置配置信息

//連接地址 private static string conn = "mongodb://192.168.11.51:40000"; //數據庫名稱 private static string dbName = "yan"; //集合名稱 private static string colName = "Demo"; //連接服務端 static MongoClient client = new MongoClient(conn); //獲取指定數據庫 static IMongoDatabase db = client.GetDatabase(dbName); //獲取指定集合 BsonDocument數據庫文檔對象 static IMongoCollection<BsonDocument> coll = db.GetCollection<BsonDocument>(colName);
使用Collection
Collection是文檔(document)的集合,可以理解為我們的數據表。而每一個文檔就是我們的一行數據。在MongoDB的驅動中,我們有兩種方式來使用Collection:
- 使用 BsonDocument 模型
- 使用自定義的實體模型
如果我們的文檔結構比較復雜,或者定義為實體模型比較困難,那么推薦使用BsonDocument模型。
如果我們的文檔結構清晰,存儲的字段也是固定的,那么推薦使用自定義的實體模型。實體對象的格式如下:
public class Entity { public ObjectId Id { get; set; } public string Name { get; set; } }
我們在獲取Collection引用的時候,需要提供一個文檔類型:var collection = db.GetCollection<Entity>("entities");
注意:用自定義類型的時候一定要有Id字段。
兩種方式都可以使用,而且各有好處,通過自定義類型的方式,可以使得collection中的文檔有比較統一的模式;
使用BsonDocument方式則可以支持更多的文檔模式,也就是說如果一個collection中的文檔擁有各種各樣的模式,那么BsonDocument方式就會更靈活。
在有了Collection之后,我們可以寫一個CURD的例子:

var collection = db.GetCollection<Entity>("entities"); var entity = new Entity { Name = "Tom" }; collection.Insert(entity); var id = entity.Id; var query = Query<Entity>.EQ(e => e.Id, id); entity = collection.FindOne(query); entity.Name = "Dick"; collection.Save(entity); var update = Update<Entity>.Set(e => e.Name, "Harry"); collection.Update(query, update); collection.Remove(query);
二、BsonDocument對象
在MongoDB.Bson命名空間下存在一個BsonDocument類,它表示MongoDB的文檔對象(二進制JSON),代表着MongoDB中不規則數據一條條實體模型。
可以使用BsonDocument對不規則數據進行操作,這個類型繼承了IEnumberable<>類,也就是說有將每一個實體模型看做一個集合,我們可以使用下標方式獲取實體模型中的值.
其部分定義:

// // 摘要: // Gets or sets a value by position. // // 參數: // index: // The position. // // 返回結果: // The value. public override BsonValue this[int index] { get; set; } // // 摘要: // Gets or sets a value by name. // // 參數: // name: // The name. // // 返回結果: // The value. public override BsonValue this[string name] { get; set; } // // 摘要: // Gets the value of an element or a default value if the element is not found. // // 參數: // name: // The name of the element. // // defaultValue: // The default value to return if the element is not found. // // 返回結果: // Teh value of the element or a default value if the element is not found. [Obsolete("Use GetValue(string name, BsonValue defaultValue) instead.")] public virtual BsonValue this[string name, BsonValue defaultValue] { get; }
其他參考:BSON
三、插入數據庫
主要有:InsertOne、InsertMany

//1、插入一條 ModelTestOne modelTestOne = new ModelTestOne() { Age = 27, Name = "huhu", Sex = "男" }; //創建數據庫鏈接 var client = new MongoClient(connectionString); //獲得數據庫、集合 var database = client.GetDatabase(dataBaseName); IMongoCollection<T> colTemp = database.GetCollection<T>(collectionName); colTemp.InsertOne(entity); //2、插入多條 var doc = new[] { new BsonDocument{ { "DepartmentName","開發部"}, { "People",new BsonArray { new BsonDocument{ { "Name", "狗娃" },{"Age",20 } }, new BsonDocument{ { "Name", "狗剩" },{"Age",22 } }, new BsonDocument{ { "Name", "鐵蛋" },{"Age",24 } } } }, {"Sum",18 }, { "dim_cm", new BsonArray { 14, 21 } } }, new BsonDocument{ { "DepartmentName","測試部"}, { "People",new BsonArray { new BsonDocument{ { "Name", "張三" },{"Age",11 } }, new BsonDocument{ { "Name", "李四" },{"Age",34 } }, new BsonDocument{ { "Name", "王五" },{"Age",33 } } } } , { "Sum",4 } , { "dim_cm", new BsonArray { 14, 21 } } }, new BsonDocument{ { "DepartmentName","運維部"}, { "People",new BsonArray { new BsonDocument{ { "Name", "閆" },{"Age",20 } }, new BsonDocument{ { "Name", "王" },{"Age",22 } }, new BsonDocument{ { "Name", "趙" },{"Age",24 } } } }, { "Sum",2 }, { "dim_cm", new BsonArray { 22.85, 30 } } } }; //創建數據庫鏈接 var client = new MongoClient(connectionString); //獲得數據庫、集合 var database = client.GetDatabase(dataBaseName); IMongoCollection<T> colTemp = database.GetCollection<T>(collectionName); colTemp.InsertMany(entity);
四、更新數據庫
文檔更新的方法有兩種,通過Save方法進行整個文檔替換,或者通過Update方法進行文檔的部分更新。
例如,找到sid為9,並且name為Will9的這個文檔,把age字段更新為27

//Save() var query = Query.And(Query.EQ("sid", 9), Query.EQ("name", "Will9")); BsonDocument Will9 = collection.FindOne(query); if (Will9 != null) { Will9["age"] = 27; collection.Save(Will9); } //Update() var query = Query.And(Query.EQ("sid", 9), Query.EQ("name", "Will9")); var update = Update.Set("age", 27); collection.Update(query, update);
五、刪除某條記錄

//刪除特定條件的文檔: var query = Query.EQ("sid", 9); collection.Remove(query); //刪除所有文檔: collection.RemoveAll();
六、查詢數據庫
通過MongoDB driver,可以支持三種查詢方法:QueryDocument、Query Builder、LINQ

public static Person Find(int id) { return mc.FindOneAs<Person>(Query.EQ("_id", id)); } public static MongoCursor<Person> FindAll() { return mc.FindAllAs<Person>(); } public static MongoCursor<Person> Select(QueryDocument q) { return mc.FindAs<Person>(q); }
統計數據個數
public static long Count(QueryDocument q) { return mc.Count(q); }
排序和分頁
public static MongoCursor<Person> SkipAndLimit(int a, int b) { return mc.FindAllAs<Person>().SetSkip(a).SetLimit(b); }