Patch REST API to Partial Update MongoDB in .NET

前端 未结 4 1158
情书的邮戳
情书的邮戳 2021-02-11 02:22

I have an object

{
  \"_id\": \"testobject\",
  \"A\": \"First line\",
  \"B\": \"Second line\",
  \"C\": \"Third line\"
}

I want to send a RE

4条回答
  •  不思量自难忘°
    2021-02-11 02:46

    You can use

    IMongoUpdate updateDoc = new UpdateDocument("$set", doc);
    collection.Update(Query.EQ("_id",id), updateDoc);
    

    However, you should be careful.

    If you first deserialize your document into SomeObject, all of the fields will get their default value (null for strings, 0 for ints etc). And if you use that object for the update, the fields that didn't exist in your json string would be updated to their default value.

    If you use

    var bsonDoc = BsonSerializer.Deserialize(jsonString);  
    IMongoUpdate updateDoc = new UpdateDocument("$set", bsonDoc);
    collection.Update(Query.EQ("_id",id), updateDoc);
    

    your document on the database will be updated only for the fields that are present in your jsonString

提交回复
热议问题