Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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.

like image 784
siva Avatar asked Feb 18 '13 13:02

siva


People also ask

How do you update a specific field in MongoDB?

To update a single field or specific fields just use the $set operator. This will update a specific field of "citiName" by value "Jakarta Pusat" that defined by $set operator.

How do you update all elements in an array in MongoDB?

To update multiple elements, use []. The[] is an all positional operator indicating that the update operator should modify all elements in the specified array field.


2 Answers

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);
like image 113
Shantanu Pandey Avatar answered Oct 06 '22 19:10

Shantanu Pandey


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);
like image 35
Kevin Versfeld Avatar answered Oct 06 '22 21:10

Kevin Versfeld