MongoDB- C# 驅動之增刪改查
MongoDB-C# 驅動之增刪改查
MongoDB.Driver是MongoDB為C#提供的一種MongoDB資料庫操作驅動,利用MongoDB.Driver 我們可以完成對MongoDB常用的增刪改查。對於MongoDB的下載及安裝部署,大家可以參見:https://www.mongodb.org/downloads 。在安裝且部署好 MongoDB之後,我們便可以使用Nuget 獲取MongoDB驅動。
新建一個控制檯程式,名為MongoDriverSample :
使用 Nuget 程式包管理控制檯,鍵入 Install-Package MongoDB.Driver 來為我們的程式安裝 MongoDB 驅動
新建一個 LogInfo 的類檔案:
using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using System; namespace MongoDriverSample { public partial class AppLog { [BsonId] public ObjectId Id { get; set; } public string Url { get; set; } public string Result { get; set; } public string ErrorMsg { get; set; } public DateTime AddDate { get; set; } public string Unme { get; set; } } }
在MongoDB中建立一個數據庫:TestDB, 建立一個Collection, 名為 AppLog(可以名稱不必要對應,可以通過後期配置對映,暫時可以設定全部一致) 。這裡我的Mongodb部署在 linux伺服器上,我使用SSH連線, 鍵入以下命令:
cd mongo
cd bin
若當前位於mongo/bin 目錄下,上兩句命令省略
mongo 127.0.0.1:27017
這個地址與埠視具體情況而定
use TestDB
db.createCollection('AppLog')
下面使用C#驅動操作資料庫:
using MongoDB.Bson; using MongoDB.Driver; using System; using System.Configuration; using System.Linq; namespace MongoDriverSample { class Program { static string connectionString = ConfigurationManager.ConnectionStrings["mongo"].ConnectionString; static string databaseName = ConfigurationManager.AppSettings["mongodb"]; static void Main(string[] args) { var mongoClient = new MongoClient(connectionString); var mongoDb = mongoClient.GetDatabase(databaseName); //查詢所有 var filter = new BsonDocument(); Action getAllAction = async () => { var result = await mongoDb.GetCollection<AppLog>("AppLog").Find(filter).ToListAsync(); //這裡我就不寫了,結果已經轉化為 List了 Console.WriteLine(result.Count()); }; getAllAction(); //按條件查詢 所有操作人Unme 為 cigarette 的資料 filter = new BsonDocument("Unme", "cigarette"); Action findByParamsAction = async () => { var result = await mongoDb.GetCollection<AppLog>("AppLog").Find(filter).ToListAsync(); Console.WriteLine(result.Count()); }; findByParamsAction(); //新增一條記錄 Action insertAction = async () => { await mongoDb.GetCollection<AppLog>("AppLog").InsertOneAsync(new AppLog { Url = "http://www.google.com", Result = "200", ErrorMsg = "", AddDate = DateTime.Now, Unme = "cigarette" }); }; insertAction(); //修改 Action updateAction = async () => { var result = await mongoDb.GetCollection<AppLog>("AppLog").UpdateOneAsync( x => x.Unme == "cigarette", Builders<AppLog>.Update.Set(x => x.Unme, "Cigarette")); Console.WriteLine(result.ModifiedCount); }; updateAction(); //刪除 Action deleteAction = async () => { var result = await mongoDb.GetCollection<AppLog>("AppLog").DeleteManyAsync( x => x.Unme == "Cigarette"); Console.WriteLine(result.DeletedCount); }; deleteAction(); Console.ReadKey(); } } }
在這裡注意一下:我使用的驅動版本為2.0, MongoDB版本為3.0,由於我使用了非同步操作,然而 Main 上是不允許使用async 關鍵字的,所以在這裡使用了Action來封裝一個無返回值的方法, 使用async來修飾,這樣就可以在方法體中使用 await 關鍵字來完成非同步操作,當然, 一般我們通常並不會去使用控制檯程式了,所以我們大可不管,瞭解即可,下面我們看看資料庫中的資料,鍵入以下命令:
db.AppLog.find().pretty()
pretty() 函式可以讓返回的文件排版,可以顯示的更加清晰:
testrs:PRIMARY> db.AppLog.find().pretty()
{
"_id" : ObjectId("55ad0430fa119e2368f92046"),
"Url" : "http://www.google.com",
"Result" : "200",
"ErrorMsg" : "",
"AddDate" : ISODate("2015-07-20T14:22:40.633Z"),
"Unme" : "cigarette"
}
{
"_id" : ObjectId("55ad0435fa119e09ac0e56e0"),
"Url" : "http://www.google.com",
"Result" : "200",
"ErrorMsg" : "",
"AddDate" : ISODate("2015-07-20T14:22:44.981Z"),
"Unme" : "cigarette"
}
以上只是使用 C# MongoDB驅動對 MongoDB的基本操作, 後續會使用驅動來寫 Web 程式的日誌以及快取等功能。