【MongoDB初识】-结合C#简单使用,驱动2.x

本文提供了使用MongoDB进行学生信息查询和更新的代码示例,包括通过名字获取单个学生实体、获取年龄大于12的学生实体列表、以及更新学生名字的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

     public static Students GetEntityByName(string conStr, string userName = "bj")
        {
            Students s = new Students();
            MongoClient client = new MongoClient(conStr);
            var db = client.GetDatabase("test");
            var collection = db.GetCollection<Students>("students");
            var query = Builders<Students>.Filter.Eq("name", "hhe");
            s = collection.Find(query).FirstAsync().Result;
            return s;
        }
        public static List<Students> GetEntityList(string conStr)
        {
            List<Students> list = new List<Students>();
            MongoClient client = new MongoClient(conStr);
            var db = client.GetDatabase("test");
            var collection = db.GetCollection<Students>("students");
            list = collection.Find(a => a.age > 12).SortBy(a => a.age).ToListAsync().Result;
            return list;
        }

        public static bool UpdateEntityByName(string conStr, string userName = "bj")
        {
            bool s = false;
            MongoClient client = new MongoClient(conStr);
            var db = client.GetDatabase("test");
            var collection = db.GetCollection<Students>("students");
            var query = Builders<Students>.Filter.Eq("name", "hhe");
            var update = Builders<Students>.Update.Set(a => a.name, "hhee");
            //Builders<Student>.Update.AddToSetEach(s => s.CoursesList, courseList)
            var ss = collection.UpdateOneAsync(query, update).Result;
            if (ss.IsAcknowledged)
            {
                s = true;
            }
            return s;
        }
        public static async Task InsertEntity(string conStr)
        {
            Students s = new Students() { name = "www1", classid = 6, age = 26 };
            MongoClient client = new MongoClient(conStr);
            var db = client.GetDatabase("test");
            var collection = db.GetCollection<Students>("students");
            await collection.InsertOneAsync(s);
        }

 

转载于:https://www.cnblogs.com/lb12081116/p/4930377.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值