How can I store decimals in MongoDB using the standard C# driver? It seems that all decimals are stored inside the database as strings.
I had issues using the RegisterSerializer approach as it complained that it already had a serializer registered, but an alternative is to write your own serialization provider and use that.
Here's the provider:
public class CustomSerializationProvider : IBsonSerializationProvider
{
private static readonly DecimalSerializer DecimalSerializer = new DecimalSerializer(BsonType.Decimal128);
private static readonly NullableSerializer NullableSerializer = new NullableSerializer(new DecimalSerializer(BsonType.Decimal128));
public IBsonSerializer GetSerializer(Type type)
{
if (type == typeof(decimal)) return DecimalSerializer;
if (type == typeof(decimal?)) return NullableSerializer;
return null; // falls back to Mongo defaults
}
}
which you need to register by calling
BsonSerializer.RegisterSerializationProvider(new CustomSerializationProvider());