Loading

使用c#对MongoDB进行查询(1)

1.BsonDocument对象

    在MongoDB.Bson命名空间下存在一个BsonDocument类,它是MongoDB的文档对象,代表着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; }

  2.连接配置

 //连接地址
        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);

3.插入数据

  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 } }

                }
            };

            coll.InsertMany(doc);

4.查询

  4.1 查询部门是开发部的信息

 //创建约束生成器
            FilterDefinitionBuilder<BsonDocument> builderFilter = Builders<BsonDocument>.Filter;
            //约束条件
            FilterDefinition<BsonDocument> filter = builder.Eq("DepartmentName", "开发部");
            //获取数据
            var result = coll.Find<BsonDocument>(filter).ToList();
            foreach (var item in result)
            {
                //取出整条值
                Console.WriteLine(item.AsBsonValue);
            }

    4.2 获取Sum大于4的数据

 //创建约束生成器
            FilterDefinitionBuilder<BsonDocument> builderFIlter = Builders<BsonDocument>.Filter;
            //约束条件
            FilterDefinition<BsonDocument> filter = builder.Gt("Sum", 4);
            var result = coll.Find<BsonDocument>(filter).ToList();
            foreach (var item in result)
            {
                //取出整条值
                Console.WriteLine(item.AsBsonValue);
            }

   4.3 And约束  

 //创建约束生成器
            FilterDefinitionBuilder<BsonDocument> builderFilter = Builders<BsonDocument>.Filter;
            //约束条件
            FilterDefinition<BsonDocument> filter = builder.And(builder.Gt("Sum", "2"), builder.Eq("DepartmentName", "运维"));
            var result = coll.Find<BsonDocument>(filter).ToList();
            foreach (var item in result)
            {
                //取出整条值
                Console.WriteLine(item.AsBsonValue);
            }

  4.4查询指定值

  //创建约束生成器
            FilterDefinitionBuilder<BsonDocument> builderFilter = Builders<BsonDocument>.Filter;
ProjectionDefinitionBuilder
<BsonDocument> builderProjection = Builders<BsonDocument>.Projection; //Include 包含某元素 Exclude 不包含某元素 ProjectionDefinition<BsonDocument> projection = builderProjection.Include("DepartmentName").Exclude("_id"); var result = coll.Find<BsonDocument>(builderFilter.Empty).Project(projection).ToList(); foreach (var item in result) { //取出整条值 Console.WriteLine(item.AsBsonValue); }

  4.5 排序

 //创建生成器
            FilterDefinitionBuilder<BsonDocument> builderFilter = Builders<BsonDocument>.Filter;
            //排序生成器
            SortDefinitionBuilder<BsonDocument> builderSort = Builders<BsonDocument>.Sort;
            //排序约束   Ascending 正序    Descending 倒序
            SortDefinition<BsonDocument> sort = builderSort.Ascending("Sum");
            var result = coll.Find<BsonDocument>(builderFilter.Empty).Sort(sort).ToList();
            foreach (var item in result)
            {
                //取出整条值
                Console.WriteLine(item.AsBsonValue);
            }

  4.6 In查询

  //创建生成器
            FilterDefinitionBuilder<BsonDocument> builderFilter = Builders<BsonDocument>.Filter;
            FilterDefinition<BsonDocument> filter = builderFilter.In("DepartmentName", new[] { "测试部", "开发部" });
            var result = coll.Find<BsonDocument>(filter).ToList();
            foreach (var item in result)
            {
                //取出整条值
                Console.WriteLine(item.AsBsonValue);
            }

   4.7  分页查询

 //创建生成器
            FilterDefinitionBuilder<BsonDocument> builderFilter = Builders<BsonDocument>.Filter;
            //分页   Skip 跳过  Limit查询多少
            var result = coll.Find<BsonDocument>(builderFilter.Empty).Skip(1).Limit(1).ToList();
            foreach (var item in result)
            {
                //取出整条值
                Console.WriteLine(item.AsBsonValue);
            }

  4.8查询总条目数

 //创建生成器
            FilterDefinitionBuilder<BsonDocument> builderFilter = Builders<BsonDocument>.Filter;
            //总条目数
            var result = coll.Find<BsonDocument>(builderFilter.Empty).Count();

  4.9Linq查询

 //创建生成器//linq
            var result = from y in coll.AsQueryable() select new { DepartmentName = y["DepartmentName"], id = y["_id"] };
            foreach (var item in result)
            {

                Console.WriteLine("DepartmentName:" + item.DepartmentName + "====Id:"+item.id);
            }

   4.10分组查询

 //创建生成器
            FilterDefinitionBuilder<BsonDocument> builderFilter = Builders<BsonDocument>.Filter;
            //分组
            var result = from y in coll.AsQueryable()  group y by  y["DepartmentName"] into s select new { DepartmentName = s.Key, Count = s.Count() };
            foreach (var item in result)
            {

                Console.WriteLine("DepartmentName:" + item.DepartmentName + "====Count:"+item.Count);
            }

  4.11连表查询

 //linq
            //连表查询   在这里是自己连自己
            var result = from u in coll.AsQueryable() join o in coll.AsQueryable() on u["_id"] equals o["_id"] select new { DepartmentName1 = u["DepartmentName"], DepartmentName2 = u["DepartmentName"] };
            foreach (var item in result)
            {

                Console.WriteLine("DepartmentName1:" + item.DepartmentName1 + "====DepartmentName2:" + item.DepartmentName2);
            }

 

posted @ 2018-03-20 19:53  莫问今朝乄  阅读(26517)  评论(14编辑  收藏  举报