更新MongoDB文档中的特定字段

19

我在小型项目中使用C#驱动程序来使用MongoDb,现在我卡在更新文档上。 尝试弄清楚如何更新字段 AVG(整数)

这是我的代码:

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?>**);

有一种简单而干净的方法可以更新特定的字段,就像使用ReplaceOne(updatedStudent)方法一样?


我认为你应该阅读MongoDB文档,它涵盖了使用C#驱动程序进行更新的所有场景。https://docs.mongodb.com/getting-started/csharp/update/ - Abhay Dixit
2个回答

46

好的,我发现有一种简单的方法可以避免在代码中写入字符串(属性名称):

OK,找到了一种无需在代码中到处编写字符串(属性名称)的简单方法:

var updateDef = Builders<Student>.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;

现在这变得容易多了。


2
同意这一点,因为这是来自官方文档的内容。https://docs.mongodb.com/manual/tutorial/update-documents/ - jet_choong

8

试试这个..& 更多信息

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

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

var update = Update<Student>.
Set(s => s.AVG, "500").
Set(s => s.FirstName, "New Name");

1
第二行创建updatedStudent的作用是什么? - Radek Strugalski

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接