MongoDB的C#驅動基本使用


MongoDB的官方C#驅動可以通過這個鏈接得到。鏈接提供了.msi和.zip兩種方式獲取驅動dll文件。

通過這篇文章來介紹C#驅動的基本數據庫連接,增刪改查操作。

在使用C#驅動的時候,要在工程中添加"MongoDB.Bson.dll"和"MongoDB.Driver.dll"的引用。同時要在代碼中加入下面兩個using語句。

using MongoDB.Bson;
using MongoDB.Driver;

 

數據庫連接

要建立數據庫連接,就一定要知道服務器的地址、端口等信息。所有的這些信息,我們都使用連接字符串表示。MongoDB的連接字符串格式如下:

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

 下面看看連接字符串中的各個字段的含義:

  • mongodb://:這個是MongoDB連接字符串的前綴
  • username:password(Optional):可選項,表示登錄用戶名和密碼,用於完成用戶安全驗證
  • hostN: 必須的指定至少一個host,表示連接到的MongoDB實例
  • portN(Optional):可選項,默認連接到27017
  • database(Optional):如果指定username:password@,連接並驗證登陸指定數據庫。若不指定,默認打開admin數據庫。
  • options(Optional):可選項,如果不使用/database,則前面需要加上/。所有連接選項都是鍵值對name=value,鍵值對之間通過&或;(分號)隔開

在這里,使用文章"MongoDB管理"中的例子,test1和test2有各自的用戶。當使用下面的連接字符串訪問的時候,可以得到正確的驗證,因為"Will1:Will1"對test1有讀寫權限。如果換成訪問test2數據庫,則會得到一個"Invalid credentials for database 'test2'"的異常輸出。

string connectionStr = "mongodb://Will1:Will1@localhost";
MongoClient client = new MongoClient(connectionStr);
MongoServer server = client.GetServer();

MongoDatabase db = server.GetDatabase("test2");
MongoCollection<BsonDocument> collection = db.GetCollection("student");
try
{
    Console.WriteLine("db name is: " + db.Name);
    Console.WriteLine("collections name is: " + collection.Name);
    Console.WriteLine("{0} items in this collection", collection.Count());
}
catch (Exception e)
{
    Console.WriteLine(e.Message);
}

 從上面的代碼中可以看到:

  • 如何獲取client和server對象
    string connectionStr = "mongodb://Will1:Will1@localhost";
    MongoClient client = new MongoClient(connectionStr);
    MongoServer server = client.GetServer();
  • 如何獲得數據庫和collection對象
    MongoDatabase db = server.GetDatabase("test2");
    MongoCollection<BsonDocument> collection = db.GetCollection("student");

     

BsonDocument對象模型

在開始增刪改查的介紹之前,要介紹一下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);

在MongoDB中,當用戶對collection進行操作的時候可以有兩種方式:

  1. 通過BsonDocument對象模型
  2. 通過自定義類型

上面已經介紹過了BsonDocument對象,在這里我們也可以使用自己自定義的類型。比如,我們可以定義一個Student類型,將該類型的對象插入到collection中。

public class Student
{
    public ObjectId _id;
    public int sid;
    public string name;
    public string gender;
    public int age;
}

注意:當是用自定義類型的時候一定要有Id字段。

上面兩種方式都可以使用,而且各有好處,通過自定義類型的方式,可以使得collection中的文檔有比較統一的模式;使用BsonDocument方式則可以支持更多的文檔模式,也就是說如果一個collection中的文檔擁有各種各樣的模式,那么BsonDocument方式就會更靈活。

 

插入數據

關於數據的插入,我們可以使用collection中的"Insert()"方法。下面插入了兩條記錄。可以通過BsonDocument對象方式插入,也可以通過自定義類型方式插入。

通過BsonDocument的方式,用戶可以自由的定義文檔的格式。例如,增加了一個“hobby”字段(Ps:不建議這么做,這樣會對文檔查詢帶來麻煩)。

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);


Student student2 = new Student();
student2.age = 27;
student2.name = "Wilber";
student2.gender = "Male";

collection.Insert(student2);

 

查詢數據

通過MongoDB driver,可以支持三種查詢方法。

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"));

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類型進行查詢。有一點不明白的就是Query使用Student強類型為什么不報錯。

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

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部分

 

更新數據

文檔更新的方法有兩種,通過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官方C# driver的基本操作。

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM