Is it possible to configure Mongo driver to keep JSON format during serialization?

The MongoDB driver for C# automatically serializes all of the properties for the given document class. Every property with “BsonElement” gets serialized. One of the fields contains a JSON property bag. The Mongo driver actually serializes it into an object.

Is it possible to somehow serialize all the fields as normal but then keep the field with the JSON property bag intact so that the JSON gets stored to MongoDB as JSON rather than some object. Ideally, I’d like to store it with the JSON intact:

Hi, @Sam_Lanza,

Welcome to the MongoDB Community Forums. I understand that you’re trying to store a JSON property bag (contained in a C# object) in MongoDB as JSON.

One point of confusion that I should clear up first. MongoDB stores BSON or “binary JSON”. BSON offers additional datatypes over traditional JSON and a more compact serialization format. In order to store the JSON property bag in MongoDB, it will have to be serialized to BSON.

In this case the .NET/C# MongoDB Driver is serializing your JSON property bag to a BSON subdocument, which is then sent over the wire (as BSON) to the MongoDB server where it is stored as BSON. The .NET/C# Driver provides a variety of ways to control the serialization process including configuration via BSON attributes, BsonClassMap<T>, and implementing your own IBsonSerializer<T>.

For example, you can apply [BsonExtraElements] attribute to a property of type BsonDocument or IDictionary<string, object> to hold any elements present in the database but without a corresponding C# property.

Since a JSON property bag can be thought of as a dictionary of string/object pairs, you could represent it in your C# object model as an IDictionary<string, object>. You can then control its serialization through Diciontary Serialization Options.

Lastly you can take full control of serialization/deserialization for a type by writing your own IBsonSerializer<T>. See Specifying the Serializer for how to configure a custom serializer.

Hopefully this provides you with some ideas of how to control the serialization of your JSON property bag and allows you to achieve your desired database format.



This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.