zoukankan      html  css  js  c++  java
  • 【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)

     
  • 相关阅读:
    [NPM] Avoid Duplicate Commands by Calling one NPM Script from Another
    [Algorithm] Dynamic programming: Find Sets Of Numbers That Add Up To 16
    [React] Refactor a Class Component with React hooks to a Function
    [Algorithm] Construct a Binary Tree and Binary Search
    设计模式(装饰者模式)
    IOS设计模式之二(门面模式,装饰器模式)
    IOS设计模式之三(适配器模式,观察者模式)
    linux内核源码阅读之facebook硬盘加速flashcache之五
    IOS设计模式之四(备忘录模式,命令模式)
    DRP总结
  • 原文地址:https://www.cnblogs.com/peterYong/p/11128722.html
Copyright © 2011-2022 走看看