Search code examples
c#mongodbmongodb-.net-driver

In C# Mongodb Driver, how to do partial update with unknown fields untouched?


Here is my code snippet:

var query = Query<MyData>.EQ(e => e.key, key);
var entity = collection.FindOne(query);

if (entity != null)
{
    entity.Value = "abc";
    // there are another 20 assignments here
    // ...
    collection.Save(entity);
}

If the collection has other fields not defined in MyData object, this will wipe out those fields. Is there any way leave the field not defined in MyData class as is?


Solution

  • I figured it out. When specify the query object, use non-strongly typed style like this

    var query = Query.EQ("myID", obj.myID);
    

    instead of

    var query = Query.EQ<MyObject>("myID", obj.myID);
    

    And specify the field to update in the update query like this

    var update = Update.SetWrapped("fieldName", obj.fieldName).SetWrapped(...)...SetWrapped(...);
    collection.Update(query, update);
    

    So the unknown fields in the mongo doc being updated will not get wiped out. I believe it is because the non-strongly typed style in the query object doesn't force to match by names.

    Thanks and hopefully this can be helpful to anyone else who has the same problem.