先貼官方文檔地址:http://mongodb.github.io/mongo-csharp-driver/html
安裝部分很簡單,nuget搜索並安裝 MongoDB.Drivergit
這是MongoDB驅動程序快速瀏覽的第一部分。在這一部分中,咱們將看看如何執行基本的CRUD(建立,讀取,更新,刪除)操做。在接下來的部分,咱們將看看執行一些管理功能。github
如下示例顯示了鏈接到本地計算機上的一個或多個服務器的三種方法。mongodb
// To directly connect to a single MongoDB server // (this will not auto-discover the primary even if it's a member of a replica set) var client = new MongoClient(); // or use a connection string var client = new MongoClient("mongodb://localhost:27017"); // or, to connect to a replica set, with auto-discovery of the primary, supply a seed list of members var client = new MongoClient("mongodb://localhost:27017,localhost:27018,localhost:27019");
該client
實例如今擁有一個到鏈接字符串中指定的服務器或服務器的鏈接池。chrome
該MongoClient
實例實際上表明瞭一個到數據庫的鏈接池; 即便有多個線程,您也只須要MongoClient類的一個實例。數據庫
一般,您只能MongoClient
爲給定羣集建立一個實例,並在整個應用程序中使用它。MongoClients
可是,只有在鏈接字符串相同的狀況下,建立多個意志仍將共享相同的鏈接池。api
要獲取數據庫,請在上面的GetDatabase
方法中指定數據庫的名稱client
。若是數據庫尚不存在,那也沒問題。它將在第一次使用時建立。瀏覽器
var database = client.GetDatabase("foo");
該database
變量如今擁有對「foo」數據庫的引用。服務器
要獲取集合以進行操做,請將集合的名稱指定給該GetCollection<TDocument>
方法database
。若是該集合尚不存在,那也不要緊。它將在第一次使用時建立。app
var collection = database.GetCollection<BsonDocument>("bar");
該collection
變量如今擁有對「foo」數據庫中「bar」集合的引用。
泛型參數TDocument
表示集合中存在的模式。上面,咱們用a BsonDocument
來表示咱們沒有預約義的模式。也可使用普通的C#對象(POCO)。有關更多信息,請參閱映射文檔。
一旦擁有collection
實例,就能夠將文檔插入到集合中。例如,請考慮如下JSON文檔; 該文檔包含一個嵌入式文檔的字段信息:
{ "name": "MongoDB", "type": "database", "count": 1, "info": { x: 203, y: 102 } }
要使用.NET驅動程序建立文檔,請使用BsonDocument
該類。您也可使用此類建立嵌入文檔。
var document = new BsonDocument { { "name", "MongoDB" }, { "type", "Database" }, { "count", 1 }, { "info", new BsonDocument { { "x", 203 }, { "y", 102 } }} };
要將文檔插入到集合中,請使用InsertOne 或者
InsertOneAsync
方法。
collection.InsertOne(document); await collection.InsertOneAsync(document);
要插入多個文檔,可使用InsertMany
or InsertManyAsync
方法。
// generate 100 documents with a counter ranging from 0 - 99 var documents = Enumerable.Range(0, 100).Select(i => new BsonDocument("counter", i)); collection.InsertMany(documents); await collection.InsertManyAsync(documents);
如今咱們已經插入了101個文檔(咱們在循環中加入了100個,加上第一個文檔),咱們能夠檢查是否所有使用Count
or CountAsync
方法。如下代碼應該將count的值設置爲101。
var count = collection.Count(new BsonDocument()); var count = await collection.CountAsync(new BsonDocument());
該方法的空BsonDocument
參數CountAsync
是一個過濾器。在這種狀況下,它是一個空過濾器,指示對全部文檔進行計數。
使用該Find
方法查詢集合。該Find
方法返回一個IFindFluent<TDocument, TProjection>
實例,爲連接查找操做選項提供流暢的接口。
要獲取集合中的第一個文檔,請調用FirstOrDefault
or FirstOrDefaultAsync
方法。FirstOrDefault
返回第一個文檔或null。這對僅適用於單個文檔的查詢或僅對第一個文檔感興趣的查詢頗有用。
如下示例打印集合中找到的第一個文檔。
var document = collection.Find(new BsonDocument()).FirstOrDefault(); Console.WriteLine(document.ToString()); var document = await collection.Find(new BsonDocument()).FirstOrDefaultAsync(); Console.WriteLine(document.ToString());
該示例應打印如下文檔:
{ "_id": ObjectId("551582c558c7b4fbacf16735") }, "name": "MongoDB", "type": "database", "count": 1, "info": { "x" : 203, "y" : 102 } }
要檢索集合中的全部文檔,請調用ToList
or ToListAsync
方法。這在預計要返回的文檔數量很小時頗有用。
var documents = collection.Find(new BsonDocument()).ToList(); var documents = await collection.Find(new BsonDocument()).ToListAsync();
若是文檔數量預計很大或者能夠迭代處理,那麼ForEachAsync
將爲每一個返回的文檔調用回調。
await collection.Find(new BsonDocument()).ForEachAsync(d => Console.WriteLine(d));
要使用同步API遍歷返回的文檔,請使用帶ToEnumerable
適配器方法的C#foreach語句:
var cursor = collection.Find(new BsonDocument()).ToCursor(); foreach (var document in cursor.ToEnumerable()) { Console.WriteLine(document); }
上面的每一個例子都會向控制檯輸出徹底相同的東西。有關迭代的更多信息,請參閱參考文檔。
咱們能夠建立一個過濾器來傳遞給Find
方法,以獲取咱們的集合中的文檔的子集。例如,若是咱們想要查找「i」字段的值爲71的文檔,咱們將執行如下操做:
var filter = Builders<BsonDocument>.Filter.Eq("i", 71); var document = collection.Find(filter).First(); Console.WriteLine(document); var document = await collection.Find(filter).FirstAsync(); Console.WriteLine(document); 它應該只打印一個文件: { "_id" : ObjectId("5515836e58c7b4fbc756320b"), "i" : 71 }
咱們還能夠從咱們的收藏中得到一組文檔。例如,若是咱們想要獲取全部文檔i > 50
,咱們能夠這樣寫:
var filter = Builders<BsonDocument>.Filter.Gt("i", 50); var cursor = collection.Find(filter).ToCursor(); foreach (var document in cursor.ToEnumerable()) { Console.WriteLine(document); } await collection.Find(filter).ForEachAsync(document => Console.WriteLine(document));
咱們也能夠獲得一個範圍,說50 < i <= 100
:
var filterBuilder = Builders<BsonDocument>.Filter; var filter = filterBuilder.Gt("i", 50) & filterBuilder.Lte("i", 100); var cursor = collection.Find(filter).ToCursor(); foreach (var document in cursor.ToEnumerable()) { Console.WriteLine(document); } await collection.Find(filter).ForEachAsync(document => Console.WriteLine(document));
咱們經過調用Sort
方法爲查詢查詢添加一個排序。下面咱們使用Exists
過濾器構建器方法和Descending
排序構建器方法對咱們的文檔進行排序:
var filter = Builders<BsonDocument>.Filter.Exists("i"); var sort = Builders<BsonDocument>.Sort.Descending("i"); var document = collection.Find(filter).Sort(sort).First(); var document = await collection.Find(filter).Sort(sort).FirstAsync();
不少時候,咱們不須要文檔中包含的全部數據。「 投影」構建器將幫助爲查找操做構建投影參數。下面咱們將排除「_id」字段並輸出第一個匹配文檔:
var projection = Builders<BsonDocument>.Projection.Exclude("_id"); var document = collection.Find(new BsonDocument()).Project(projection).First(); Console.WriteLine(document.ToString()); var document = await collection.Find(new BsonDocument()).Project(projection).FirstAsync(); Console.WriteLine(document.ToString());
MongoDB支持許多更新運算符。
要最多更新1個文檔(若是沒有匹配過濾器,則可能爲0),請使用UpdateOne
or UpdateOneAsync
方法指定過濾器和更新文檔。在這裏,咱們更新符合過濾器的第一個文檔i == 10
並將值設置i
爲110
:
var filter = Builders<BsonDocument>.Filter.Eq("i", 10); var update = Builders<BsonDocument>.Update.Set("i", 110); collection.UpdateOne(filter, update); await collection.UpdateOneAsync(filter, update);
要更新與過濾器匹配的全部文檔,請使用UpdateMany
或UpdateManyAsync
方法。在這裏,咱們增長的價值i
由100
地方i < 100
。
var filter = Builders<BsonDocument>.Filter.Lt("i", 100); var update = Builders<BsonDocument>.Update.Inc("i", 100); var result = collection.UpdateOne(filter, update); if (result.IsModifiedCountAvailable) { Console.WriteLine(result.ModifiedCount); } var result = await collection.UpdateManyAsync(filter, update); if (result.IsModifiedCountAvailable) { Console.WriteLine(result.ModifiedCount); }
更新方法返回一個UpdateResult
提供有關操做的信息,包括更新修改的文檔數量。
要刪除最多1個文檔(若是沒有匹配過濾器,則能夠爲0)使用DeleteOne
或DeleteOneAsync
方法:
var filter = Builders<BsonDocument>.Filter.Eq("i", 110); collection.DeleteOne(filter); await collection.DeleteOneAsync(filter);
要刪除與過濾器匹配的全部文檔,請使用DeleteMany
或DeleteManyAsync
方法。這裏咱們刪除全部文件,其中i >= 100
:
var filter = Builders<BsonDocument>.Filter.Gte("i", 100); var result = collection.DeleteMany(filter); Console.WriteLine(result.DeletedCount); var result = await collection.DeleteManyAsync(filter); Console.WriteLine(result.DeletedCount);
刪除方法返回一個DeleteResult
提供有關操做的信息,包括刪除的文檔數量。
有兩種類型的批量操做:
有序批量操做。
按順序執行全部操做,並在第一個錯誤中執行錯誤。
無序批量操做。
執行全部操做並報告任何錯誤。無序批量操做不保證執行順序。
讓咱們看看使用有序和無序操做的兩個簡單例子:
var models = new WriteModel<BsonDocument>[] { new InsertOneModel<BsonDocument>(new BsonDocument("_id", 4)), new InsertOneModel<BsonDocument>(new BsonDocument("_id", 5)), new InsertOneModel<BsonDocument>(new BsonDocument("_id", 6)), new UpdateOneModel<BsonDocument>( new BsonDocument("_id", 1), new BsonDocument("$set", new BsonDocument("x", 2))), new DeleteOneModel<BsonDocument>(new BsonDocument("_id", 3)), new ReplaceOneModel<BsonDocument>( new BsonDocument("_id", 3), new BsonDocument("_id", 3).Add("x", 4)) }; // 1. Ordered bulk operation - order of operation is guaranteed collection.BulkWrite(models); // 2. Unordered bulk operation - no guarantee of order of operation collection.BulkWrite(models, new BulkWriteOptions { IsOrdered = false }); // 1. Ordered bulk operation - order of operation is guaranteed await collection.BulkWriteAsync(models); // 2. Unordered bulk operation - no guarantee of order of operation await collection.BulkWriteAsync(models, new BulkWriteOptions { IsOrdered = false });