Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use decimal type in MongoDB

Tags:

c#

mongodb

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

like image 201
Ramon de Klein Avatar asked Apr 18 '17 13:04

Ramon de Klein


People also ask

Is MongoDB a decimal?

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.

What data type is used for decimal numbers?

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.

Can decimal data type store decimal values?

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.

What data type is number in MongoDB?

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.


2 Answers

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:

  • MongoDB server should be at least v3.4.
  • MongoCSharpDriver should be at least v2.4.3.
  • Database should have 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))); 
like image 182
Ramon de Klein Avatar answered Sep 17 '22 14:09

Ramon de Klein


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;} 
like image 39
Erik Kinding Avatar answered Sep 20 '22 14:09

Erik Kinding