c# - Patch REST API to Partial Update MongoDB in .NET -
i have object
{ "_id": "testobject", "a": "first line", "b": "second line", "c": "third line" }
i want send rest patch request api update 1 of these properties
{ "_id": "testobject", "c": "forth line" }
this gets parsed class
public class someobject { public string { get; set; } public string b { get; set; } public string c { get; set; } }
i need update existing document in mongodb updating property c
.
i create update definition 1 record
updatedefinition<someobject> update = builders<someobject>.update.set(x => x.c, <value of property c>)
or hard code check on each property see if empty
ilist<updatedefinition<someobject>> updates = new list<updatedefinition<someobject>>(); if (!string.isnullorempty(c)) { updates.add(updatedefinition<someobject> update = builders<someobject>.update.set(x => x.c, <value of property c>)); } if (!string.isnullorempty(c)) { updates.add(updatedefinition<someobject> update = builders<someobject>.update.set(x => x.c, <value of property c>)); }
however, if have many properties , many sub properties large fast. other issue if set value of property intentionally empty not update record @ due looking field non-empty.
how can dynamically partial updates mongodb documents in .net have generic patch api call can take of parameters document has , update properties specified?
you can use
imongoupdate updatedoc = new updatedocument("$set", doc); collection.update(query.eq("_id",id), updatedoc);
however, should careful.
if first deserialize document someobject, of fields default value (null strings, 0 ints etc). , use object update, fields didn't exist in json string updated default value.
if use
var bsondoc = bsonserializer.deserialize<bsondocument>(jsonstring); imongoupdate updatedoc = new updatedocument("$set", bsondoc); collection.update(query.eq("_id",id), updatedoc);
your document on database updated fields present in jsonstring
Comments
Post a Comment