close

在 ASP.NET 上使用 MongoDB 進行 CRUD 的操作,MongoDB 對 C# 語言進行了支援並提供了 C# 操作的 Driver,在接下來的步驟裡就是要透過使用 MongoDB C# Driver 來進行操作。

 

下載MongoDB C# Driver

有兩種方法來安裝C# Driver

 1. 下載安裝 

我使用的是直接下載安裝 http://docs.mongodb.org/getting-started/csharp/client/

 

2. 透過 NuGet 直接安裝

https://www.nuget.org/packages/mongocsharpdriver

 

PM> Install-Package mongocsharpdriver

 

MongoDB C# Driver 包含了兩個 DLL 分別是 MongoDB.Driver 與 MongoDB.Bson,Driver 是相依於 Bson 之上,用於處理 Bson 規範的相關工作,例如 I/O、序列化或針對BSON 模型的處理等等,Bson 能夠單獨使用,必要時再透過 Driver 進行操作。

 

安裝MongoDB C# Driver

把MongoDB.DLL 加入References

 

在References 資料夾按右鍵 選"Add Reference...."

 2015-09-15_165031

2015-09-15_165051

 

加入後

 

 2015-09-15_165539

使用 MongoDB 基本上會 using 以下兩個命名空間。

 using MongoDB.Bson;
using MongoDB.Driver;

 

連接資料庫、 新增、讀取、更新、刪除操作

 

 連接資料庫

    首先建立一個 MongoProduct Entity 類別 ,此類別將用於處理存放操作所需用到的屬性,如下。

2015-09-15_191634

 

 

     由毽子中透過 MongoClient 物件依序取得 Server、Database、Collection 物件,如下。

2015-09-15_193608

以上步驟就是先透過建立 MongoClient 物件取得連線後,在使用 MongoClient 類別的 GetServer() 方法取得服務參考,最後再透過 MongoServer 物件的 GetDatabase(connectionString) 方法取得 MongoDatabase 物件參考,有了 MongoDatabase 物件就可以對該資料庫進行操作了,而上面填入的 test 資料庫則是根據你要操作的資料庫填入資料庫名稱,如 test 資料庫並不存在時,將會自動建立一個 test 資料庫,最後直接取得 MongoProduct Collection 物件。

 

新增

新增直接呼叫 MongoCollection 類別提供的 Insert 方法傳入 Entity 物件即可。

2015-09-15_192225

讀取

直接呼叫 MongoCollection 類別提供的 FindAll 和 FindOne 方法

 

FindAll

2015-09-15_192740

FindOne 這邊有用 Query  這個需要using MongoDB.Driver.Builders 才可以。

2015-09-15_192751  

更新

呼叫 MongoCollection 類別提供的 save 方法

2015-09-15_193643  

刪除

呼叫 MongoCollection 類別提供的 remove 方法

2015-09-15_192558

以上就是 MongoDB 基本的 CRUD 操作方法,實際應用上還有許多方法跟變化可以使用,日後將再繼續補充。

範例程式碼

https://github.com/kennethhutw/MongodbInDotNet_CSharpDriver

 

 

 

 

 

 

 

 

 

 

 

arrow
arrow

    Kenneth 發表在 痞客邦 留言(1) 人氣()