更新mongodb文档中的特定字段

我使用C#驱动程序在小项目中使用MongoDb,现在我坚持更新文档。 试图弄清楚如何更新字段AVG (int)

这是我的代码:

IMongoCollection studentCollection = db.GetCollection("studentV1"); Student updatedStudent = new Student() { AVG = 100, FirstName = "Shmulik" }); studentCollection.UpdateOne( o=>o.FirstName == student.FirstName, ****); 

有一种简单而干净的方法来更新特定字段,如方法ReplaceOne(updatedStudent)

试试这个……以及更多信息

 IMongoCollection studentCollection = db.GetCollection("studentV1"); Student updatedStudent = new Student() { AVG = 100, FirstName = "Shmulik" }); var update = Update. Set(s => s.AVG, "500"). Set(s => s.FirstName, "New Name"); 

好的,所以发现有很简单的方法可以在整个代码中没有写字符串(属性名称):

 var updateDef = Builders.Update.Set(o => o.AVG, student.AVG); studentCollection.UpdateOne(o => o.FirstName == student.FirstName, updateDef); 

我不知道这需要很长时间才能找到(+2天),但我终于找到了答案 :

 var filter = Builders.Filter.Eq(x => x.AgendaId, agendaId); var update = Builders.Update.Set(x => x.Items.Single(p => p.Id.Equals(itemId)).Title, title); var result = _collection.UpdateOneAsync(filter, update).Result; 

现在它更容易了。