19

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

moshe770
  • 753
  • 1
  • 7
  • 10
  • I think you should read mongodb docs, it has covered all scenario related to update using c# driver. https://docs.mongodb.com/getting-started/csharp/update/ – Abhay Dixit Feb 28 '17 at 11:55

2 Answers2

46

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.

Community
  • 1
  • 1
moshe770
  • 753
  • 1
  • 7
  • 10
  • 2
    Agree on this as this is from the official documentation https://docs.mongodb.com/manual/tutorial/update-documents/ – jet_choong Nov 28 '18 at 03:17
8

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");
Community
  • 1
  • 1
Darshak
  • 859
  • 7
  • 18