【MongoDB】在C#中使用


一、MongoClient類

     在2.10.0版本中引入了MongoClient類,同時在其API中也說明了Mongo類會在將來的版本中被MongoClient替換(Note: This class has been superseded by MongoClient, and may be deprecated in a future release.)。故在這次調整中,也對原先的Mongodb部分做了相應的修改。

      MongoClient被設計成線程安全、可以被多線程共享的通常訪問數據庫集群的應用只需要一個實例,所以這次調整我們設計成單例形式。如果出於某些原因,你決定使用多個實例,請注意: 所有資源使用限制(最大連接數等等)對每個MongoClient都適用;銷毀一個實例時,請確認調用MongoClient.close()方法來清理資源。

設置配置信息

//連接地址
        private static string conn = "mongodb://192.168.11.51:40000";
        //數據庫名稱
        private static string dbName = "yan";
        //集合名稱
        private static string colName = "Demo";
        //連接服務端
       static  MongoClient client = new MongoClient(conn);
        //獲取指定數據庫
       static IMongoDatabase db = client.GetDatabase(dbName);
        //獲取指定集合   BsonDocument數據庫文檔對象
       static  IMongoCollection<BsonDocument> coll = db.GetCollection<BsonDocument>(colName);
View Code

使用Collection

Collection是文檔(document)的集合,可以理解為我們的數據表。而每一個文檔就是我們的一行數據。在MongoDB的驅動中,我們有兩種方式來使用Collection

  1. 使用 BsonDocument 模型
  2. 使用自定義的實體模型

如果我們的文檔結構比較復雜,或者定義為實體模型比較困難,那么推薦使用BsonDocument模型

如果我們的文檔結構清晰,存儲的字段也是固定的,那么推薦使用自定義的實體模型。實體對象的格式如下:

public class Entity
{
    public ObjectId Id { get; set; }
    public string Name { get; set; }
}

我們在獲取Collection引用的時候,需要提供一個文檔類型:var collection = db.GetCollection<Entity>("entities");

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

兩種方式都可以使用,而且各有好處,通過自定義類型的方式,可以使得collection中的文檔有比較統一的模式;

使用BsonDocument方式則可以支持更多的文檔模式,也就是說如果一個collection中的文檔擁有各種各樣的模式,那么BsonDocument方式就會更靈活。

在有了Collection之后,我們可以寫一個CURD的例子:

var collection = db.GetCollection<Entity>("entities");

var entity = new Entity { Name = "Tom" };
collection.Insert(entity);
var id = entity.Id;

var query = Query<Entity>.EQ(e => e.Id, id);
entity = collection.FindOne(query);

entity.Name = "Dick";
collection.Save(entity);

var update = Update<Entity>.Set(e => e.Name, "Harry");
collection.Update(query, update);

collection.Remove(query);
View Code

二、BsonDocument對象

在MongoDB.Bson命名空間下存在一個BsonDocument類,它表示MongoDB的文檔對象(二進制JSON),代表着MongoDB中不規則數據一條條實體模型。

可以使用BsonDocument對不規則數據進行操作,這個類型繼承了IEnumberable<>類,也就是說有將每一個實體模型看做一個集合,我們可以使用下標方式獲取實體模型中的值.

其部分定義:

//
        // 摘要:
        //     Gets or sets a value by position.
        //
        // 參數:
        //   index:
        //     The position.
        //
        // 返回結果:
        //     The value.
        public override BsonValue this[int index] { get; set; }
        //
        // 摘要:
        //     Gets or sets a value by name.
        //
        // 參數:
        //   name:
        //     The name.
        //
        // 返回結果:
        //     The value.
        public override BsonValue this[string name] { get; set; }
        //
        // 摘要:
        //     Gets the value of an element or a default value if the element is not found.
        //
        // 參數:
        //   name:
        //     The name of the element.
        //
        //   defaultValue:
        //     The default value to return if the element is not found.
        //
        // 返回結果:
        //     Teh value of the element or a default value if the element is not found.
        [Obsolete("Use GetValue(string name, BsonValue defaultValue) instead.")]
        public virtual BsonValue this[string name, BsonValue defaultValue] { get; }
View Code

其他參考:BSON

三、插入數據庫

主要有:InsertOne、InsertMany

//1、插入一條
 ModelTestOne modelTestOne = new ModelTestOne()
            {
                Age = 27,
                Name = "huhu",
                Sex = ""
            };
            
     //創建數據庫鏈接
                var client = new MongoClient(connectionString);
                //獲得數據庫、集合
                var database = client.GetDatabase(dataBaseName);
                IMongoCollection<T> colTemp = database.GetCollection<T>(collectionName);
                colTemp.InsertOne(entity);


//2、插入多條
var doc = new[]
            {
                new BsonDocument{
                    { "DepartmentName","開發部"},
                    { "People",new  BsonArray
                        {
                            new BsonDocument{ { "Name", "狗娃" },{"Age",20 } },
                             new BsonDocument{ { "Name", "狗剩" },{"Age",22 } },
                              new BsonDocument{ { "Name", "鐵蛋" },{"Age",24 } }
                        }
                    },
                    {"Sum",18 },
                      { "dim_cm", new BsonArray { 14, 21 } }


                },
                 new BsonDocument{
                    { "DepartmentName","測試部"},
                    { "People",new  BsonArray
                        {
                            new BsonDocument{ { "Name", "張三" },{"Age",11 } },
                             new BsonDocument{ { "Name", "李四" },{"Age",34 } },
                              new BsonDocument{ { "Name", "王五" },{"Age",33 } }
                        }
                    }
                     ,
                     { "Sum",4 }
                     ,
                       { "dim_cm", new BsonArray { 14, 21 } }

                },
                  new BsonDocument{
                    { "DepartmentName","運維部"},
                    { "People",new  BsonArray
                        {
                            new BsonDocument{ { "Name", "" },{"Age",20 } },
                             new BsonDocument{ { "Name", "" },{"Age",22 } },
                              new BsonDocument{ { "Name", "" },{"Age",24 } }
                        }
                    },
                     { "Sum",2 },
                       { "dim_cm", new BsonArray { 22.85, 30 } }

                }
            };

          //創建數據庫鏈接
                var client = new MongoClient(connectionString);
                //獲得數據庫、集合
                var database = client.GetDatabase(dataBaseName);
                IMongoCollection<T> colTemp = database.GetCollection<T>(collectionName);
                colTemp.InsertMany(entity);            
View Code

四、更新數據庫

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

五、刪除某條記錄

//刪除特定條件的文檔:
var query = Query.EQ("sid", 9);
collection.Remove(query);

//刪除所有文檔:
collection.RemoveAll();
View Code

六、查詢數據庫

通過MongoDB driver,可以支持三種查詢方法:QueryDocument、Query Builder、LINQ

   public static Person Find(int id)
        {
            return mc.FindOneAs<Person>(Query.EQ("_id", id));
        }

        public static MongoCursor<Person> FindAll()
        {
            return mc.FindAllAs<Person>();
        }

        public static MongoCursor<Person> Select(QueryDocument q)
        {
            return mc.FindAs<Person>(q);
        }
View Code

 統計數據個數

 public static long Count(QueryDocument q)
  {
       return mc.Count(q);
 }

排序和分頁

public static MongoCursor<Person> SkipAndLimit(int a, int b)
        {
            return mc.FindAllAs<Person>().SetSkip(a).SetLimit(b);
        }

 參考:使用c#對MongoDB進行查詢(1)

 

 


免責聲明!

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



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