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

     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