2017-02-28 76 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; 

現在更容易了。

相關問題