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.
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.
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.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With