When writing new documents or updating existing ones, the mongodb-c-sharp-driver outputs generic bson/json for non-primitive types
"myList" : [
{"value" : "..."},
{"value" : "..."}
]
When using the Update.Set()
statement however, the driver wraps the actual data with type info
"myList" : {
"_t" : "System.Collections.Generic.List`1[[Models.MyModel, Common]]",
"_v" : [
{"value" : "..."},
{"value" : "..."}
]
}
I want to avoid this wrapping, since the same dataset is potentially used by other drivers/languages in a distributed environment.
Is the only way to achieve that to fetch the entire document, update and write back?
Related old questions here, here and here.
UPDATE
This code triggers the type wrappers
public void Set(ObjectId id, string name, object value)
{
var query = Query.EQ("_id", id);
var update = Update.Set(name, value.ToBsonDocument());
_collection.Update(query, update);
}
And here's a generic method I came up with. It is able to set primitive types as well as complex types without type info:
public void Set<T>(ObjectId id, string name, T value)
{
var query = Query.EQ("_id", id);
var update = Update.Set(name, ConvertToBsonValue<T>(value));
_collection.Update(query, update);
}
public BsonValue ConvertToBsonValue<T>(T value)
{
try
{
return BsonValue.Create(value);
}
catch
{
return value.ToBsonDocument<T>();
}
}
When using Generics instead of objects, the conversion to BsonValue is not necessary.