C# 更新mongodb文档中的特定字段

C# 更新mongodb文档中的特定字段,c#,mongodb,mongodb-query,C#,Mongodb,Mongodb Query,我使用C#driver在小项目中使用MongoDb,现在我坚持更新文档。 试图找出如何更新字段平均值(int) 这是我的密码: IMongoCollection<Student> studentCollection = db.GetCollection<Student>("studentV1"); Student updatedStudent = new Student() { AVG = 100, FirstName = "Shmulik" }); studentC

我使用C#driver在小项目中使用MongoDb,现在我坚持更新文档。 试图找出如何更新字段平均值(int)

这是我的密码:

IMongoCollection<Student> studentCollection = db.GetCollection<Student>("studentV1");

Student updatedStudent = new Student() { AVG = 100, FirstName = "Shmulik" });

studentCollection.UpdateOne(
        o=>o.FirstName == student.FirstName,
            **<What should I write here?>**);
IMongoCollection studentCollection=db.GetCollection(“studentV1”);
Student updatedStudent=new Student(){AVG=100,FirstName=“Shmulik”});
studentCollection.UpdateOne(
o=>o.FirstName==student.FirstName,
****);
有一种简单而干净的方法可以更新特定字段,比如方法
ReplaceOne(updatedstudion)

试试这个..&

IMongoCollection studentCollection=db.GetCollection(“studentV1”);
Student updatedStudent=new Student(){AVG=100,FirstName=“Shmulik”});
var update=更新。
设置(s=>s.AVG,“500”)。
Set(s=>s.FirstName,“新名称”);

好的,我们发现有一种简单的方法可以做到这一点,而无需在代码上写字符串(属性名称):

var updateDef=Builders.Update.Set(o=>o.AVG,student.AVG);
studentCollection.UpdateOne(o=>o.FirstName==student.FirstName,updateDef);
我不知道要花这么长时间才能找到(+2天),但我终于找到了 下面的句子:

var filter = Builders<TempAgenda>.Filter.Eq(x => x.AgendaId, agendaId);
var update = Builders<TempAgenda>.Update.Set(x => x.Items.Single(p => p.Id.Equals(itemId)).Title, title);
var result = _collection.UpdateOneAsync(filter, update).Result;
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=\u collection.UpdateOneAsync(filter,update.result);

现在更容易了。

我认为您应该阅读mongodb文档,它涵盖了与使用c#driver进行更新相关的所有场景。同意这一点,因为这是官方文档中创建updatedStudent的第二行的角色是什么?
var updateDef = Builders<Student>.Update.Set(o => o.AVG, student.AVG);

studentCollection.UpdateOne(o => o.FirstName == student.FirstName, updateDef);
var filter = Builders<TempAgenda>.Filter.Eq(x => x.AgendaId, agendaId);
var update = Builders<TempAgenda>.Update.Set(x => x.Items.Single(p => p.Id.Equals(itemId)).Title, title);
var result = _collection.UpdateOneAsync(filter, update).Result;