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

How to write this update request to update a mongo entry in C #.

db.collection.update({ "S_Id" : 110 },{ "Name" : "Name1","Batch" : "43","Date":"9/2/2011",  "Status" : 0 }); 

I'm trying to do it

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

I did the right thing or how should I do it, please do the right way.

+5
source share
2 answers

In your example, you potentially overwrite the value updatefor each option, so only one update command will be sent to col1.Update().

you will want to use a method Update.Combine, something implicit: (untested and a little 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);
+6
source

now it is changed to:

    FilterDefinitionBuilder<BsonDocument> builder = Builders<BsonDocument>.Filter;
    FilterDefinition<BsonDocument> filter;

    filter = builder.Eq("_id",BsonObjectId.Create(objectid));

// or search field

    var update = Builders<BsonDocument>.Update
 .Set("key1", "value1")
 .Set("key2", "value2")
 .CurrentDate("lastModified"); 

  Collection.UpdateOne(filter, update);
+1
source

All Articles