1. 程式人生 > >MongoDB學習筆記(三)--MongoDB的C#驅動的基本使用

MongoDB學習筆記(三)--MongoDB的C#驅動的基本使用

官方C#驅動:https://github.com/mongodb/mongo-csharp-driver/releases
在使用C#驅動時,要在專案中新增”MongoDB.Bson.dll”和”MongoDB.Driver.dll”的引用。同時要在程式碼中加入下面兩個using語句。

using MongoDB.Bson;
using MongoDB.Driver;

1.資料庫連線
要建立資料庫連線,就一定要知道伺服器的地址、埠等資訊。所有的這些資訊,都使用連線字串表示。MongoDB的連線字串格式如下:

mongodb://[username:[email protected]
]host1[:port1][,host2[:port2],…[,hostN[:portN]]][/[database][?options]]

下面看看連線字串中的各個欄位的含義:
• mongodb://:這個是MongoDB連線字串的字首
• username:password(Optional):可選項,表示登入使用者名稱和密碼,用於完成使用者安全驗證
• hostN: 必須的指定至少一個host,表示連線到的MongoDB例項
• portN(Optional):可選項,預設連線到27017
• database(Optional):如果指定username:[email protected]

,連線並驗證登陸指定資料庫。若不指定,預設開啟admin資料庫。
• options(Optional):可選項,如果不使用/database,則前面需要加上/。所有連線選項都是鍵值對name=value,鍵值對之間通過&或;(分號)隔開
這裡寫圖片描述
2. BsonDocument物件模型
在MongoDB collection中,每個文件都可以看作一個Bson(Binary JSON)物件,所以在驅動中有個一個BsonDocument型別,可以通過下面的方式生成一個文件,並且通過Add方法新增鍵/值對。通過這種方式生成的BsonDocument物件可以直接插入collection中。
方式一:

BsonDocument student1 = new BsonDocument();
student1.Add("sid", 10);
student1.Add("name", "Will10");
student1.Add("gender", "Male");
student1.Add("age", 26);

方式二:

  BsonDocument stu = new BsonDocument
    {
        {"sid", 10},
        {"name", "Will10"},
        {"gender", "Male"},
        {"age", 26}
     };

在MongoDB中,當用戶對collection進行操作的時候可以有兩種方式:
1. 通過BsonDocument物件模型
2. 通過自定義型別
上面已經介紹過了BsonDocument物件,在這裡也可以使用自己自定義的型別。比如,可以定義一個Student型別,將該型別的物件插入到collection中。
這裡寫圖片描述
這裡寫圖片描述

注意:當是用自定義型別的時候一定要有Id欄位。
上面兩種方式都可以使用,而且各有好處,通過自定義型別的方式,可以使得collection中的文件有比較統一的模式;使用BsonDocument方式則可以支援更多的文件模式,也就是說如果一個collection中的文件擁有各種各樣的模式,那麼BsonDocument方式就會更靈活。
3.插入資料
關於資料的插入,可以使用collection中的”Insert()”方法。下面插入了兩條記錄。可以通過BsonDocument物件方式插入,也可以通過自定義型別方式插入。
通過BsonDocument的方式,使用者可以自由的定義文件的格式。例如,增加了一個“hobby”欄位(Ps:不建議這麼做,這樣會對文件查詢帶來麻煩)。
(1).BsonDocument物件方式插入:

BsonDocument student1 = new BsonDocument();
student1.Add("sid", 10);
student1.Add("name", "Will10");
student1.Add("gender", "Male");
student1.Add("age", 26);
student1.Add("hobby", new BsonArray() { "swimming","reading"});

collection.Insert(student1);
(2).自定義型別方式插入
Student student2 = new Student();
student2.age = 27;
student2.name = "Wilber";
student2.gender = "Male";

collection.Insert(student2);

4.查詢資料
通過MongoDB driver,可以支援三種查詢方法。
(1).QueryDocument
這種方式的查詢,類似在MongoDB shell中的條件查詢。例如,查詢年齡大於20的學生

QueryDocument queryDocument = new QueryDocument("age", new QueryDocument("$gt",20));
foreach (var student in collection.Find(queryDocument))
{
    Console.WriteLine(student);
}

當查詢條件為多個的時候,例如,查詢年齡大於20的男學生

QueryDocument queryDocument = new QueryDocument(new BsonElement("age", new QueryDocument("$gt", 20)), new BsonElement("gender","Male"));

(2).Query Builder
Query Builder是一種更簡潔的方式,當通過這種方式查詢的時候,需要使用driver中的builder來生成query。所以,要引用下面using語句
using MongoDB.Driver.Builders;
通過下面的語句,可以查詢年齡大於20的學生

var query = Query.GT("age", 20);
 foreach (var student in collection.Find(query))
 {
     Console.WriteLine(student);
 }

查詢年齡大於20的男學生
var query = Query.And(Query.GT(“age”, 20), Query.EQ(“gender”, “Male”));
當然,也可以進行 強型別 查詢,但是這種查詢是有前提條件的, “要求文件中的欄位必須是自定義型別欄位的子集,也就是要求文件可以轉化為特定型別” 。例如,前面插入了一個文件還有”hobby”這個key,如果使用下面的方法,就會產生一個異常,提示Student型別沒有hobby這個欄位。

var query = Query<Student>.GT(e => e.age, 20);
foreach (var student in collection.FindAs<Student>(query))
{
    Console.WriteLine(student);
}

在這種情況下,可以使用BsonDocument型別進行查詢。

var query = Query<Student>.GT(e => e.age, 20);
foreach (var student in collection.FindAs<BsonDocument>(query))
{
    Console.WriteLine(student);
}

(3).LINQ支援
在driver的1.8 release之後,官方驅動就可以支援LINQ操作了。只需要通過下面的using語句,就可以支援LINQ的方式進行查詢了。
using MongoDB.Driver.Linq;
所以,可以查詢年齡大於20的學生,也可以通過下面方式實現(注意,同樣要保證所有的document都可以轉化為Student型別)

var linquery = from e in collection.AsQueryable<Student>()
             where e.age > 20
             select e;

var linquery1 = collection.AsQueryable<Student>().Where(e => e.age > 20);

MongoDB文件中有很多的LINQ查詢操作,請參閱 MongoDB文件的LINQ部分
5.更新資料
文件更新的方法有兩種,通過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);

6.刪除資料
刪除資料的操作相對比較簡單。
刪除特定條件的文件:

var query = Query.EQ("sid", 9);
collection.Remove(query);

刪除所有文件:

collection.RemoveAll();

提示:三種查詢方式中,Query Builder最靈活,使用LINQ方式查詢是,最好所有的文件都有統一的模式,這樣就可以方便的使用自定義型別。