Serialization
On this page
Overview
In this guide, you can learn how to use the MongoDB .NET/C# Driver to perform serialization. Serialization is the process of mapping a C# object to a BSON document for storage in MongoDB.
Serializers
Serializers are classes that handle the translation of C# objects to and
from BSON documents. Serializers implement the IBsonSerializer
interface. The .NET/C# Driver has many built-in serializers made to handle
primitive types, collection types, and custom classes.
For a full list of available serializers, see the Serializers namespace API documentation.
ObjectSerializer
The ObjectSerializer
class allows serialization and deserialization only of types
that are considered safe. When you construct an ObjectSerializer
,
you can pass in a delegate of type Func<Type, bool>
. This delegate
accepts an object type and returns a boolean value indicating whether the
type is safe for serialization.
In most cases, you should pass in the ObjectSerializer.DefaultAllowedTypes()
delegate. This method returns true for a number of well-known
framework types that we have deemed safe. To serialize custom types,
create a boolean expression that evaluates to true
for the
types you want to include. Then, add this expression to the end of the
delegate you pass to the ObjectSerializer
constructor.
In the following example,
the ObjectSerializer
will serialize and deserialize any type that is allowed by
ObjectSerializer.DefaultAllowedTypes()
or whose full name begins with
"MyNamespace"
:
var objectSerializer = new ObjectSerializer(type => ObjectSerializer.DefaultAllowedTypes(type) || type.FullName.StartsWith("MyNamespace")); BsonSerializer.RegisterSerializer(objectSerializer);
To allow anonymous types to be serialized, add the boolean expression
type.FullName.StartsWith("<>f__AnonymousType"))
to your delegate,
as shown in the following example:
var objectSerializer = new ObjectSerializer(type => ObjectSerializer.DefaultAllowedTypes(type) || type.FullName.StartsWith("<>f__AnonymousType")); BsonSerializer.RegisterSerializer(objectSerializer);
You should create and register your ObjectSerializer
at the start of your program,
before doing anything else.
Serializer Registry
The serializer registry contains all registered serializers that are available to your application. Many of the built-in serializers are automatically registered to the serializer registry during startup of your application. However, before you can use a custom serializer, you must add it to the serializer registry, as shown in the following example:
BsonSerializer.RegisterSerializer(new CustomTypeSerializer());
To access the serializer registry, use the SerializerRegistry
property
of the BsonSerializer
class as follows:
var intSerializer = BsonSerializer.SerializerRegistry.GetSerializer<int>();
Important
The serializer registry is a global registry. This means that you cannot use multiple registries in a single application.
Custom Serializers
To create your own custom serializer, implement the IBsonSerializer
base class, set
the ValueType
member, and override the Deserialize()
and Serialize()
methods.
The following code example shows a custom BsonRegularExpression
serializer:
class CustomRegularExpressionSerializer : IBsonSerializer { public Type ValueType => typeof(Regex); public object Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) { var type = context.Reader.CurrentBsonType; switch (type) { case BsonType.RegularExpression: return context.Reader.ReadRegularExpression().AsRegex; case BsonType.String: var pattern = context.Reader.ReadString() return new Regex(pattern); default: throw new NotSupportedException($"Cannot convert a {type} to a RegularExpression."); } } public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, object value) { var regex = (Regex) value; context.Writer.WriteRegularExpression(regex); } }
Opt-in Interfaces
The .NET/C# Driver has several optional interfaces that your custom serializer class can implement, depending on the type of data the serializer handles.
IBsonIdProvider
The IBsonIdProvider
interface provides the GetDocumentId()
and SetDocumentId()
methods, and is useful if the object you are serializing uses an _id
type other than ObjectId
.
IBsonDocumentSerializer
Implementing the IBsonDocumentSerializer interface enables the driver to access the member information of the object you are serializing. This allows the driver to properly construct type-safe queries when using a custom serializer.
IBsonArraySerializer
Implementing the IBsonArraySerializer interface enables the driver to access serialization information for individual items in an array.
Additional Information
To learn more about using the .NET/C# Driver to serialize C# objects, see the following pages:
To learn more about any of the methods or types discussed in this guide, see the following API documentation: