Update specific field in mongodb document

烈酒焚心 提交于 2019-12-22 03:35:12

问题


I using C# driver to use MongoDb in small projects, and now I stuck with updating documents. trying to figure out how to update the field AVG (int)

here is my code:

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

there is simple and clean way to update specific field(s) like the method ReplaceOne(updatedStudent)?


回答1:


Try this..& 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");



回答2:


ok, so found out there is easy way to do it without write strings all over the code (Property names):

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

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

I didn't know it's take so long to find (+2 days), but I finally found this answer with the lines:

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;

and now it's much easier.



来源:https://stackoverflow.com/questions/42507640/update-specific-field-in-mongodb-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!