Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update specific field in mongodb document

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

like image 570
moshe770 Avatar asked Feb 28 '17 11:02

moshe770


2 Answers

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.

like image 92
moshe770 Avatar answered Sep 28 '22 12:09

moshe770


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");
like image 30
Darshak Avatar answered Sep 28 '22 11:09

Darshak