Search code examples
c#mongodbdictionarybson

Dictionary<string, object>-to-BsonDocument conversion omitting _t field


I'm using ToBsonDocument extension method from MongoDB.Bson to convert this Dictionary:

        var dictionary = new Dictionary<string, object> {{"person", new Dictionary<string, object> {{"name", "John"}}}};
        var document = dictionary.ToBsonDocument();

And here's the resulting document:

  { "person" : 
      { "_t" : "System.Collections.Generic.Dictionary`2[System.String,System.Object]", 
        "_v" : { "name" : "John" } } }

Is there a way to get rid of these _t/_v stuff? I would like the resulting document to look like this:

  { "person" : { "name" : "John" } }

UPD: I've found the code in DictionaryGenericSerializer:

if (nominalType == typeof(object))
{
    var actualType = value.GetType();
    bsonWriter.WriteStartDocument();
    bsonWriter.WriteString("_t", TypeNameDiscriminator.GetDiscriminator(actualType));
    bsonWriter.WriteName("_v");
    Serialize(bsonWriter, actualType, value, options); // recursive call replacing nominalType with actualType
    bsonWriter.WriteEndDocument();
    return;
}

So, it seems that there are not too many options with this serializer when the value type is object.


Solution

  • You shall first serialize to JSON and then to BSON,

    var jsonDoc = Newtonsoft.Json.JsonConvert.SerializeObject(dictionary);
    var bsonDoc = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(jsonDoc);