C#操作MongoDB


8.1)下載安裝

 想要在C#中使用MongoDB,首先得要有個MongoDB支持的C#版的驅動。C#版的驅動有很多種,如官方提供的,samus。 實現思路大都類似。這里我們先用官方提供的mongo-csharp-driver ,當前版本為1.4.1

下載地址:http://github.com/mongodb/mongo-csharp-driver/downloads

編譯之后得到兩個dll

 MongoDB.Driver.dll:顧名思義,驅動程序

 MongoDB.Bson.dll:序列化、Json相關

 然后在我們的程序中引用這兩個dll。

 下面的部分簡單演示了怎樣使用C#對MongoDB進行增刪改查操作。

 8.2)連接數據庫:

 在連接數據庫之前請先確認您的MongoDB已經開啟了。

//數據庫連接字符串 const string strconn = "mongodb://127.0.0.1:27017"; //數據庫名稱 const string dbName = "cnblogs"; //創建數據庫鏈接 MongoServer server = MongoDB.Driver.MongoServer.Create(strconn); //獲得數據庫cnblogs MongoDatabase db = server.GetDatabase(dbName);

8.3)插入數據:

好了數據打開了,現在得添加數據了,我們要添加一條User“記錄”到 Users集合中。

在MongoDB中沒有表的概念,所以在插入數據之前不需要創建表。

但我們得定義好要插入的數據的模型Users

復制代碼
Users.cs:
    public class Users { public ObjectId _id;//BsonType.ObjectId 這個對應了 MongoDB.Bson.ObjectId     public string Name { get; set; } public string Sex { set; get; } }
復制代碼

_id 屬性必須要有,否則在更新數據時會報錯:“Element '_id' does not match any field or property of class”。

 好,現在看看添加數據的代碼怎么寫:

復制代碼
public void Insert() { //創建數據庫鏈接 MongoServer server = MongoDB.Driver.MongoServer.Create(strconn); //獲得數據庫cnblogs MongoDatabase db = server.GetDatabase(dbName); Users users = new Users(); users.Name = "xumingxiang"; users.Sex = "man"; //獲得Users集合,如果數據庫中沒有,先新建一個 MongoCollection col = db.GetCollection("Users"); //執行插入操作 col.Insert<Users>(users); }
復制代碼

8.4)更新數據

復制代碼
public void Update() { //創建數據庫鏈接 MongoServer server = MongoDB.Driver.MongoServer.Create(strconn); //獲得數據庫cnblogs MongoDatabase db = server.GetDatabase(dbName); //獲取Users集合 MongoCollection col = db.GetCollection("Users"); //定義獲取“Name”值為“xumingxiang”的查詢條件 var query = new QueryDocument { { "Name", "xumingxiang" } }; //定義更新文檔 var update = new UpdateDocument { { "$set", new QueryDocument { { "Sex", "wowen" } } } }; //執行更新操作 col.Update(query, update); } 注意:千萬要注意查詢條件和數據庫內的字段類型保持一致,否則將無法查找到數據。如:如果Sex是整型,一點要記得將值轉換為整型。
復制代碼

8.5)刪除數據

復制代碼
public void Delete() { //創建數據庫鏈接 MongoServer server = MongoDB.Driver.MongoServer.Create(strconn); //獲得數據庫cnblogs MongoDatabase db = server.GetDatabase(dbName); //獲取Users集合 MongoCollection col = db.GetCollection("Users"); //定義獲取“Name”值為“xumingxiang”的查詢條件 var query = new QueryDocument { { "Name", "xumingxiang" } }; //執行刪除操作 col.Remove(query); }
復制代碼

8.6)查詢數據

復制代碼
public void Query() { //創建數據庫鏈接 MongoServer server = MongoDB.Driver.MongoServer.Create(strconn); //獲得數據庫cnblogs MongoDatabase db = server.GetDatabase(dbName); //獲取Users集合 MongoCollection col = db.GetCollection("Users"); //定義獲取“Name”值為“xumingxiang”的查詢條件 var query = new QueryDocument { { "Name", "xumingxiang" } }; //查詢全部集合里的數據 var result1 = col.FindAllAs<Users>(); //查詢指定查詢條件的第一條數據,查詢條件可缺省。 var result2 = col.FindOneAs<Users>(); //查詢指定查詢條件的全部數據 var result3 = col.FindAs<Users>(query); }
復制代碼

 

 

 

 

 

 

MongoDb在C#中使用

 

 

復制代碼
using System;
using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; using System.Data; using System.Data.SqlClient; using MongoDB.Bson; using MongoDB.Driver; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { //連接信息 string conn = "mongodb://localhost"; string database = "demoBase"; string collection = "demoCollection"; MongoServer mongodb = MongoServer.Create(conn);//連接數據庫 MongoDatabase mongoDataBase = mongodb.GetDatabase(database);//選擇數據庫名 MongoCollection mongoCollection = mongoDataBase.GetCollection(collection);//選擇集合,相當於表 mongodb.Connect(); //普通插入 var o = new { Uid = 123, Name = "xixiNormal", PassWord = "111111" }; mongoCollection.Insert(o); //對象插入 Person p = new Person { Uid = 124, Name = "xixiObject", PassWord = "222222" }; mongoCollection.Insert(p); //BsonDocument 插入 BsonDocument b = new BsonDocument(); b.Add("Uid", 125); b.Add("Name", "xixiBson"); b.Add("PassWord", "333333"); mongoCollection.Insert(b); Console.ReadLine(); } } class Person { public int Uid; public string Name; public string PassWord; } }
復制代碼

 

結果:

都是上述配置寫的,程序會自動建立對應的庫和集合。

下面的操作不上完整代碼了:

復制代碼
            /*--------------------------------------------- * sql : SELECT * FROM table *--------------------------------------------- */ MongoCursor<Person> p = mongoCollection.FindAllAs<Person>(); /*--------------------------------------------- * sql : SELECT * FROM table WHERE Uid > 10 AND Uid < 20 *--------------------------------------------- */ QueryDocument query = new QueryDocument(); BsonDocument b = new BsonDocument(); b.Add("$gt", 10); b.Add("$lt", 20); query.Add("Uid", b); MongoCursor<Person> m = mongoCollection.FindAs<Person>(query); /*----------------------------------------------- * sql : SELECT COUNT(*) FROM table WHERE Uid > 10 AND Uid < 20 *----------------------------------------------- */ long c = mongoCollection.Count(query); /*----------------------------------------------- * sql : SELECT Name FROM table WHERE Uid > 10 AND Uid < 20 *----------------------------------------------- */ QueryDocument query = new QueryDocument(); BsonDocument b = new BsonDocument(); b.Add("$gt", 10); b.Add("$lt", 20); query.Add("Uid", b); FieldsDocument f = new FieldsDocument(); f.Add("Name", 1); MongoCursor<Person> m = mongoCollection.FindAs<Person>(query).SetFields(f); /*----------------------------------------------- * sql : SELECT * FROM table ORDER BY Uid DESC LIMIT 10,10 *----------------------------------------------- */ QueryDocument query = new QueryDocument(); SortByDocument s = new SortByDocument(); s.Add("Uid", -1);//-1=DESC MongoCursor<Person> m = mongoCollection.FindAllAs<Person>().SetSortOrder(s).SetSkip(10).SetLimit(10);
復制代碼

 

官方驅動查詢:

復制代碼
Query.All("name", "a", "b");//通過多個元素來匹配數組  Query.And(Query.EQ("name", "a"), Query.EQ("title", "t"));//同時滿足多個條件  Query.EQ("name", "a");//等於  Query.Exists("type", true);//判斷鍵值是否存在  Query.GT("value", 2);//大於>  Query.GTE("value", 3);//大於等於>=  Query.In("name", "a", "b");//包括指定的所有值,可以指定不同類型的條件和值  Query.LT("value", 9);//小於<  Query.LTE("value", 8);//小於等於<=  Query.Mod("value", 3, 1);//將查詢值除以第一個給定值,若余數等於第二個給定值則返回該結果  Query.NE("name", "c");//不等於  Query.Nor(Array);//不包括數組中的值  Query.Not("name");//元素條件語句  Query.NotIn("name", "a", 2);//返回與數組中所有條件都不匹配的文檔  Query.Or(Query.EQ("name", "a"), Query.EQ("title", "t"));//滿足其中一個條件  Query.Size("name", 2);//給定鍵的長度  Query.Type("_id", BsonType.ObjectId );//給定鍵的類型  Query.Where(BsonJavaScript);//執行JavaScript  Query.Matches("Title",str);//模糊查詢 相當於sql中like -- str可包含正則表達式
復制代碼

 

 

 

 

 

 

 

在C#中使用samus驅動操作MongoDB

再來介紹一款第三方驅動samus,這是一款使用使用較多的驅動,更新頻率比較快,samus驅動除了支持一般形式的操作之外,還支持Linq 和Lambda 表達式。

下載地址:https://github.com/samus/mongodb-csharp

下載回來編譯得到兩個dll

MongoDB.dll          驅動的主要程序

MongoDB.GridFS.dll    用於存儲大文件。

這里我們引用MongoDB.dll  即可。關於MongoDB.GridFS.dll 本文用不到,暫不介紹,無視它。

其連接數據庫以及CRUD操作如下:

復制代碼
//數據庫連接字符串const string strconn = "mongodb://127.0.0.1:27017"; //數據庫名稱const string dbName = "cnblogs"; //定義數據庫MongoDatabase db; /// <summary>/// 打開數據庫鏈接 /// </summary>public void GetConnection() { //定義Mongo服務 Mongo mongo = new Mongo(strconn); //打開連接 mongo.Connect(); //獲得數據庫cnblogs,若不存在則自動創建 db = mongo.GetDatabase(dbName) as MongoDatabase; } /// <summary>/// 添加數據 /// </summary>public void Insert() { var col = db.GetCollection<Users>(); //或者 //var col = db.GetCollection("Users"); Users users = new Users(); users.Name = "xumingxiang"; users.Sex = "man"; col.Insert(users); } /// <summary>/// 更新數據 /// </summary>public void Update() { var col = db.GetCollection<Users>(); //查出Name值為xumingxiang的第一條記錄 Users users = col.FindOne(x => x.Name == "xumingxiang"); //或者 //Users users = col.FindOne(new Document { { "Name", "xumingxiang" } }); users.Sex = "women"; col.Update(users, x => x.Sex == "man"); } /// <summary>/// 刪除數據 /// </summary>public void Delete() { var col = db.GetCollection<Users>(); col.Remove(x => x.Sex == "man"); ////或者 ////查出Name值為xumingxiang的第一條記錄 //Users users = col.FindOne(x => x.Sex == "man"); //col.Remove(users);} /// <summary>/// 查詢數據 /// </summary>public void Query() { var col = db.GetCollection<Users>(); var query = new Document { { "Name", "xumingxiang" } }; //查詢指定查詢條件的全部數據 var result1 = col.Find(query); //查詢指定查詢條件的第一條數據 var result2 = col.FindOne(query); //查詢全部集合里的數據 var result3 = col.FindAll(); }
復制代碼

 

 

 

QueryDocument 的常用查詢:

[csharp] view plain copy

/*---------------------------------------------* sql : SELECT * FROM table WHERE ConfigID > 5 AND ObjID = 1 

*--------------------------------------------*/              

QueryDocument query = new QueryDocument();              

BsonDocument b = new BsonDocument();             

b.Add("$gt", 5);                         

query.Add("ConfigID", b);  

query.Add("ObjID", 1);  

MongoCursor<Person> m = mongoCollection.FindAs<Person>(query);  

  /*---------------------------------------------             

* sql : SELECT * FROM table WHERE ConfigID > 5 AND ConfigID < 10            

*---------------------------------------------              

*/              

QueryDocument query = new QueryDocument();              

BsonDocument b = new BsonDocument();              

b.Add("$gt", 5);     

b.Add("$lt", 10);                   

query.Add("ConfigID", b);  

MongoCursor<Person> m = mongoCollection.FindAs<Person>(query); 

 

public class News  {        public int _id { getset; }        public int count { getset; }        public string news { getset; }        public DateTime time { getset; }

}  MongoCursor<BsonDocument> allDoc = coll.FindAllAs<BsonDocument>(); BsonDocument doc = allDoc.First(); //BsonDocument類型參數  MongoCursor<News> allNews = coll.FindAllAs<News>();  News aNew = allNews.First(); //News類型參數  News firstNews = coll.FindOneAs<News>(); //查找第一個文檔  QueryDocument query = new QueryDocument(); //定義查詢文檔 query.Add("_id"10001); query.Add("count"1); MongoCursor<News> qNews = coll.FindAs<News>(query);   BsonDocument bd = new BsonDocument();//定義查詢文檔 count>2 and count<=4 bd.Add("$gt"2); bd.Add("$lte"4); QueryDocument query_a = new QueryDocument(); query_a.Add("count",bd); FieldsDocument fd = new FieldsDocument(); fd.Add("_id"0);

fd.Add("count"1); fd.Add("time"1); MongoCursor<News> mNewss = coll.FindAs<News>(query_a).SetFields(fd);//只返回count和time var time = BsonDateTime.Create("2011/9/5 23:26:00"); BsonDocument db_t = new BsonDocument(); db_t.Add("$gt", time); QueryDocument qd_3 = new QueryDocument(); qd_3.Add("time", db_t); MongoCursor<News> mNews = coll.FindAs<News>(qd_3);//


免責聲明!

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



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