MongoDB 学习 6 组件 MongoDB.Driver,查

查询的内容多一些,单独写

查询一条

        static void GetWorker1()
        {
            var client = new MongoClient(conString);
            var db = client.GetDatabase(dbName);
            FilterDefinitionBuilder<Worker> filterBuilder = Builders<Worker>.Filter;
            FilterDefinition<Worker> filter = filterBuilder.Eq(doc => doc.name, "雷震子");
            var worker = db.GetCollection<Worker>("worker").Find(filter).FirstOrDefault();
        }

这里的eq是等于,相应的还有lt,lte等等方法。

查询集合,带分页

        static void GetWorker2()
        {
            var client = new MongoClient(conString);
            var db = client.GetDatabase(dbName);
            FilterDefinitionBuilder<Worker> filterBuilder = Builders<Worker>.Filter;
            FilterDefinition<Worker> filter = filterBuilder.Eq(doc => doc.gender, "");
            var workers = db.GetCollection<Worker>("worker").Find(filter).SortBy(a=>a.age).Skip(0).Limit(4).ToList();
        }

skip要跳过的条数,limit取几条。

获取记录条数

var count = db.GetCollection<Worker>("worker").Find(filter).CountDocuments();

获取指定字段

        static void GetWorker2()
        {
            var client = new MongoClient(conString);
            var db = client.GetDatabase(dbName);
            FilterDefinitionBuilder<Worker> filterBuilder = Builders<Worker>.Filter;
            FilterDefinition<Worker> filter = filterBuilder.Eq(doc => doc.gender, "");
            ProjectionDefinitionBuilder<Worker> projectBuilder = Builders<Worker>.Projection;
            ProjectionDefinition<Worker> projection = projectBuilder.Include(doc => doc.name)
                .Include(doc => doc.age)
                .Include(doc => doc.gender);
            var workers1 = db.GetCollection<Worker>("worker").Find(filter).Project(projection).SortBy(a=>a.age).Skip(0).Limit(3).ToList();
            foreach (var w in workers1)
            {
              var worker =   BsonSerializer.Deserialize<Worker>(w);
            }
        }

用ProjectionDefinitionBuilder和ProjectionDefinition投影,指定要获取name,age,gender,然后循环反序列化成实体类。

不过这样有点麻烦,所以建议用linq,匿名类直接搞定。

            var workers3 = db.GetCollection<Worker>("worker").AsQueryable().Select(doc => new
            {
                Name = doc.name,
                Age = doc.age,
                Gender = doc.gender
            });
            foreach (var w in workers3)
            {
                
            }

 

MongoDB 学习 6 组件 MongoDB.Driver,查

上一篇:linux gdb调试C/C++多线程死锁的定位


下一篇:Sqli-Labs-GET部分【Less1-10】