更新mongodb文档中的特定字段

mos*_*770 13 c# mongodb mongodb-query

我使用C#驱动程序在小项目中使用MongoDb,现在我坚持更新文档.试图弄清楚如何更新字段AVG(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?>**);
Run Code Online (Sandbox Code Playgroud)

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

mos*_*770 34

好的,所以发现有一个简单的方法来做到这一点,而无需在整个代码中写入字符串(属性名称):

var updateDef = Builders<Student>.Update.Set(o => o.AVG, student.AVG);

studentCollection.UpdateOne(o => o.FirstName == student.FirstName, updateDef);
Run Code Online (Sandbox Code Playgroud)

我不知道要花很长时间才能找到(+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;
Run Code Online (Sandbox Code Playgroud)

现在它更容易了.

  • 同意这一点,因为这是来自官方文档 https://docs.mongodb.com/manual/tutorial/update-documents/ (2认同)

Dar*_*hak 5

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

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");
Run Code Online (Sandbox Code Playgroud)