以下是參考 官方網站所提供的 CSharp sample 教學的心得。
- 為了說明方便,先在mongoDB 中的test資料庫上建一個Table : "Employee",如下圖(RockMongo的介面)
 
內容是一個JSON 的物件,包含 id,name,age 等屬性
接者一件很重要的是就是下載libary.(官方網站上有link,在Download 項目下,連結見*) 不論是下載安裝版還是編譯版,之後記得將 MongoDB.Bson.dll 和 MongoDB.Driver.dll 記得引用
以下是相關的功能:
1. 連結資料庫: 以下是本機且沒有設帳密
      //在code 中
 using MongoDB.Driver;
 using MongoDB.Driver.Builders;
 MongoServer Server;
 MongoDatabase test;
Server = MongoServer.Create(); // connect to localhost
        test = Server.GetDatabase("test");
2. 取得所有項目
     
      MongoCollection<BsonDocument> employees = test.GetCollection<BsonDocument>("Employee");
      var query = new QueryDocument(); // 查詢內容為空,可以想像是Sql 中的 select *
      string _result = "";
      foreach (BsonDocument _employee in employees.Find(query)){
           
                _result += _employee.ToJson() +"/n";
      }
3. 查詢特定項目
          MongoCollection<BsonDocument>  employees = test.GetCollection<BsonDocument>("Employee");
          var query = Query.GT("age", "20");      // 查詢 age 大於 20, 其他等於是eq 還有很多請參照文件的說明*  
            string _result = "";  
            foreach (BsonDocument _employee in employees.Find(query)){ 
                
                _result += _employee.ToJson() + "/n";
            }
            
4. 查詢特定項目並存到物件中
要先定義好物件,且變數要和資料庫中的JSON一致才能轉換,先定義TEmployee
 public class TEmployee{
        public MongoDB.Bson.ObjectId Id { get; private set; }    // Id 的屬性使用Mongodb的 objectId      
        public string name { get; set; }
        public string age { get; set; }   
    }
接下來一樣搜尋age大於20的物件,不過先將物件存到 TEmployee中
           MongoCollection<temployee> ee = test.GetCollection<temployee>("Employee"); 
            var query = Query.GT("age", "20");
            string _result = "";
            foreach (TEmployee _employee in ee.Find(query)){           
     
                _result += _employee.name + "/n";
            }
5. 新增項目
新增一個BsonDocument物件,再Insert到資料庫
新增一個BsonDocument物件,再Insert到資料庫
           MongoCollection<temployee> ee = test.GetCollection<temployee>("Employee"); 
           BsonDocument newEmployee = new BsonDocument { { "name", "Dannie" }, { "age", "47" } };
     
           employees.Insert(newEmployee);
     
參考:
* CSharp Driver Serialization Tutorial

沒有留言:
張貼留言