溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

MongoDB的C#驅動的基本使用

發(fā)布時間:2021-08-25 17:20:20 來源:億速云 閱讀:136 作者:chen 欄目:大數(shù)據(jù)

這篇文章主要介紹“MongoDB的C#驅動的基本使用”,在日常操作中,相信很多人在MongoDB的C#驅動的基本使用問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”MongoDB的C#驅動的基本使用”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

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

using MongoDB.Bson;using MongoDB.Driver;

數(shù)據(jù)庫連接

要建立數(shù)據(jù)庫連接,就一定要知道服務器的地址、端口等信息。所有的這些信息,我們都使用連接字符串表示。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@,連接并驗證登陸指定數(shù)據(jù)庫。若不指定,默認打開admin數(shù)據(jù)庫。

  • options(Optional):可選項,如果不使用/database,則前面需要加上/。所有連接選項都是鍵值對name=value,鍵值對之間通過&或;(分號)隔開

在這里,使用文章"MongoDB管理"中的例子,test1和test2有各自的用戶。當使用下面的連接字符串訪問的時候,可以得到正確的驗證,因為"Will1:Will1"對test1有讀寫權限。如果換成訪問test2數(shù)據(jù)庫,則會得到一個"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();
  • 如何獲得數(shù)據(jù)庫和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. 通過自定義類型

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

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

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

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

插入數(shù)據(jù)

關于數(shù)據(jù)的插入,我們可以使用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);

查詢數(shù)據(jù)

通過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,如果使用下面的方法,就會產(chǎn)生一個異常,提示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的學生,也可以通過下面方式實現(xiàn)(注意,同樣要保證所有的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部分

更新數(shù)據(jù)

文檔更新的方法有兩種,通過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);

刪除數(shù)據(jù)

刪除數(shù)據(jù)的操作相對比較簡單。

刪除特定條件的文檔:

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

刪除所有文檔:

collection.RemoveAll();

到此,關于“MongoDB的C#驅動的基本使用”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關知識,請繼續(xù)關注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI