How to update a document only fields dynamically passed ?

263 views
Skip to first unread message

Ittipan Langkulanon

unread,
Sep 19, 2016, 5:56:00 AM9/19/16
to mongodb-user
There are solution like this to update specific attribute but it was a static code
var filter = Builders<BsonDocument>.Filter.Eq("_id", doc.Id);
var update = Builders<BsonDocument>.Update.Set("i", 110);
await collection.UpdateOneAsync(filter, update);

Another way is replace entire document except for the _id field
var filter = Builders<BsonDocument>.Filter.Eq("_id", doc.Id);
await collection.ReplaceOneAsync(filter, doc, new UpdateOptions { IsUpsert = true });

But I can't found any solution like the ReplaceOneAsync that did not replace entire document but just only passed fields in doc object.

John Murphy

unread,
Oct 4, 2016, 3:16:40 AM10/4/16
to mongodb-user

Hello Ittipan,

The three methods to update documents of a collection are UpdateOneAsync, UpdateManyAsync and ReplaceOneAsync.

As you are aware if you wish to update specific fields you would need to use an UpdateDefinitionBuilder with multiple calls to Set each value you wish to update. Example code utilising multiple Set calls would look like this:

 var FieldOne = "dynamicFieldA";
 var FieldTwo = "dynamicFieldB";

 var filters = Builders<BsonDocument>.Filter.Eq("_id", doc.Id);
 var updateValues = Builders<BsonDocument>.Update
                                          .Set(FieldOne, "a")
                                          .Set(FieldTwo, "b");

 await collection.UpdateOneAsync(filters, updateValues);

One alternative would be to load the document you wish to modify, followed by calling BsonDocument.Merge with overwriteExistingElements set to true in order to merge your changes. You would then use the one of the patterns you previously mentioned in order to persist the new document to the database.

Regards,
John Murphy


Reply all
Reply to author
Forward
0 new messages