I’m trying to build a generic method to handle all my partial updates via MongoDB C# driver, using the following method:
public bool UpdateObject<T>(UpdatableObject<T> updatableObject)
where T : new()
{
var builder = GenerateMongoUpdateBuilder(updatableObject.ModifiedFields);
var collection = GetCollection<T>();
var result = collection.Update(Query.EQ("_id", BsonValue.Create(updatableObject.Id)), builder, new MongoUpdateOptions { Flags = UpdateFlags.Multi });
return result.UpdatedExisting;
}
private static UpdateBuilder GenerateMongoUpdateBuilder(Dictionary<string, object> modifiedFields)
{
var builder = new UpdateBuilder();
foreach (var modifiedField in modifiedFields)
{
var type = modifiedField.Value.GetType();
if (type.IsPrimitive || type.IsValueType || (type == typeof(string)))
{
builder.Set(modifiedField.Key, BsonValue.Create(modifiedField.Value));
}
else
{
builder.Set(modifiedField.Key, modifiedField.Value.ToBsonDocument());
}
}
return builder;
}
I had to struggle for a while until I found the solution to handle primitive types via BsonValue and non-primitive types via BsonDocument. Everything worked well, until…We’ve created an object which holds a dictionary. The insert works perfectly, but once it goes into update (using this method) – it cannot be deserialized any more. Looking at the object in the Mongo before and after the update indicates that it’s not the same object anymore – after the update it has additional _t field holds “System.Collections.Generic.Dictionary`2[System.String,[SomeObject, SomeObjectAssembly]]”
So I’m starting to question my implementation…
Any idea what am I doing wrong?
Thanks,
Nir.
With the courtesy of Robert Stam, the issue was resolved. It’s all described in the Jira item.
Thank you!