How can I store decimals in MongoDB using the standard C# driver? It seems that all decimals are stored inside the database as strings.
MongoDb added support for Decimal data type in 3.4 version. It is also available from the shell. 3.4 adds support for the decimal128 format with the new decimal data type. The decimal128 format supports numbers with up to 34 decimal digits (i.e. significant digits) and an exponent range of −6143 to +6144.
Numbers that contain a decimal point are stored in a data type called REAL. Variables that use the real data type can accept both positive and negative numbers with a decimal place.
Note: The decimal data type is suitable for storing currency data where the required range of values or number of digits to the right of the decimal point exceeds the capacities of the money data type. For display purposes, a currency sign cannot be specified for decimal values.
Integer: In MongoDB, the integer data type is used to store an integer value. We can store integer data type in two forms 32 -bit signed integer and 64 – bit signed integer.
MongoDB doesn't properly support decimals until MongoDB v3.4. Before this version it stored decimals as strings to avoid precision errors.
Pre v3.4 Store decimals as strings, but this prevents arithmetic operations. Operators as $min
, $avg
, ... won't be available. If precision is not a big deal, then you might be able to switch to double
.
v3.4+ You need to make sure the following preconditions are true:
featureCompatibilityVersion
set to '3.4'
. If your database has been created by an older MongoDB version and you have upgraded your server to v3.4 your database might still be on an older version.If you have all the properties set, then register the following serializers to use the decimal128
type:
BsonSerializer.RegisterSerializer(typeof(decimal), new DecimalSerializer(BsonType.Decimal128)); BsonSerializer.RegisterSerializer(typeof(decimal?), new NullableSerializer<decimal>(new DecimalSerializer(BsonType.Decimal128)));
I recently ran in to this problem. I solved it by simply annotating my object like this:
[BsonRepresentation(BsonType.Decimal128)] public decimal Price {get; set;}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With