How to use decimal type in MongoDB

前端 未结 4 710
终归单人心
终归单人心 2020-11-29 11:07

How can I store decimals in MongoDB using the standard C# driver? It seems that all decimals are stored inside the database as strings.

4条回答
  •  臣服心动
    2020-11-29 11:45

    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());
    

提交回复
热议问题