.Net Core对MongoDB数据库增删改查

//实体类
public class User
{//转载请保留 http://www.luofenming.com/show.aspx?id=ART2021021300001
    public MongoDB.Bson.ObjectId Id { get; set; }
    public string name { get; set; }
    public int age { get; set; }
}
//using MongoDB.Bson;
//using MongoDB.Driver;
 public void Add(User t)
 {
     MongoClient client = new MongoClient("mongodb://192.168.1.105:27017/");
     //获取database
     IMongoDatabase mydb = client.GetDatabase("myDb");
     //获取collection
     var collection = mydb.GetCollection<User>("userinfos");
     collection.InsertOne(t);
 }

 public void Read()
 {
     MongoClient client = new MongoClient("mongodb://192.168.1.105:27017/");
     //获取database
     IMongoDatabase mydb = client.GetDatabase("myDb");
     //获取collection
     var collection = mydb.GetCollection<User>("userinfos");

     //方法一
     //List<User> list1 = collection.Find(x => x.name == "罗分明").Skip(0).Limit(10).SortByDescending(x => x.age).ToList();
     //方法二
     var filterDic = new Dictionary<string, object> { { "name", "罗分明" }};
     var filter = new BsonDocument(filterDic);
     var list1 = collection.Find(filter).Skip(0).Limit(10).ToList();
     Console.WriteLine(JsonConvert.SerializeObject(list1));

 }
 public void Update(ObjectId id)
 {
     //string转ObjectId  MongoDB.Bson.ObjectId.Parse("60279eac5d25f5b17d85e7e9");
     //或者MongoDB.Bson.ObjectId.TryParse("60279eac5d25f5b17d85e7e9");
     MongoClient client = new MongoClient("mongodb://192.168.1.105:27017/");
     //获取database
     IMongoDatabase mydb = client.GetDatabase("myDb");
     //获取collection
     var collection = mydb.GetCollection<User>("userinfos");
     var doc = collection.Find(x => x.Id == id).Skip(0).Limit(1).ToList();
     if (!doc.Any())
         return;
     var updateBuilder = Builders<User>.Update;

     var update = updateBuilder.Set(x => x.name, "罗分明")
     .Set(x => x.age, 20);

     UpdateResult result = collection.UpdateOne(x => x.Id == id, update);
 }

 public void Delete(ObjectId id)
 {
     MongoClient client = new MongoClient("mongodb://192.168.1.105:27017/");
     //获取database
     IMongoDatabase mydb = client.GetDatabase("myDb");
     //获取collection
     var collection = mydb.GetCollection<User>("userinfos");
     DeleteResult result = collection.DeleteOne(x => x.Id == id);
 }

评论