Update specific field in mongodb document

2019-04-21 14:50发布

问题:

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.