siva
siva

Reputation: 243

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

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.

Upvotes: 9

Views: 14711

Answers (2)

Shantanu Pandey
Shantanu Pandey

Reputation: 69

it has now modified to:

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

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

// or field to search

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

  Collection.UpdateOne(filter, update);

Upvotes: 0

Kevin Versfeld
Kevin Versfeld

Reputation: 720

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

Upvotes: 14

Related Questions