2017-02-28 75 views
2

我使用C#驱动程序在小型项目中使用MongoDb,现在我坚持更新文档。 试图找出如何更新现场AVG(INT)更新mongodb文档中的特定字段

这里是我的代码:

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)更新特定领域(S)?

+0

我想你应该阅读mongodb文档,它已经涵盖了与使用c#驱动程序更新相关的所有场景。 https://docs.mongodb.com/getting-started/csharp/update/ – Aby

回答

1

试试这个.. & for more info

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

确定,所以发现有简单的方法来做到这一点没有写串遍代码(属性名):

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

studentCollection.UpdateOne(o => o.FirstName == student.FirstName, updateDef); 

我没不知道找到这么长时间(+2天),但我终于找到了this answer 与行:

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; 

现在更容易了。

相关问题