How to write update query to update multiple fields in mongodb?

c#, mongodb

Solution

In your example, you are potentially overwriting the value of `update` for each option, so will only be sending a single update command to `col1.Update()`.

you will want to use the `Update.Combine` method, something vaguely like this: (untested, and a bit ugly...)

    var updateValues = new List<UpdateBuilder>();
    if (Named != null) { updateValues.Add(Update.Set("Name", "Name1")); }
    if (Date != null) { updateValues.Add(Update.Set("Date", "18/02/2013")); }
    if (Batch != null) { updateValues.Add(Update.Set("Batch", 43)); }
    IMongoUpdate update = Update.Combine(updateValues);
    coll.Update(query, update);

Problem

How to write this update query for updating a mongo record in c#. ``` db.collection.update({ "S_Id" : 110 },{ "Name" : "Name1","Batch" : "43","Date":"9/2/2011", "Status" : 0 }); ``` I'am trying like this ``` IMongoUpdate update = new UpdateDocument(); if (Named != null) { update = Update.Set("Name", "Name1"); } if (Date != null) { update = Update.Set("Date", "18/02/2013"); } if (Batch != null) { update = Update.Set("Batch",43); } coll.Update(query, update); ``` was I'am doing correct or in what way i have to do it, please make me the correct way to proceed.

Original source