C# 修改MongoDB数据

更新时间:2022-12-25 12:15
实体类
public class User
{
    public MongoDB.Bson.ObjectId Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}
修改数据方法
public void Update(ObjectId id)
{
    //string转ObjectId  MongoDB.Bson.ObjectId.Parse("60279eac5d25f5b17d85e7e9");
    //或者MongoDB.Bson.ObjectId.TryParse("60279eac5d25f5b17d85e7e9");
    MongoClient client = new MongoClient("mongodb://lqwvje:123456@192.168.1.242:27017");
    //获取database
    IMongoDatabase mydb = client.GetDatabase("myDB");
    //获取collection
    var collection = mydb.GetCollection<User>("user");
    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);
}