Search code examples
c#mongodbmongodb-.net-driverbson

Setting default MongoDb/Bson representation for all decimals to double


I am helping to write a C# application to analyse financial data. Internally all the numbers are stored as decimal, however when we persist them to our mongodb database, we would like them to be stored as doubles, rather than strings. I know I can do this for individual fields by applying the [BsonRepresentation(BsonType.Double)] attribute to each decimal field, but I keep forgetting when adding new decimal values.

Is there any way of making this the default representation for all decimal numbers?


Solution

  • For anyone coming to this question now, it's worth mentioning that since v3.4, Mongo now natively supports storing Decimal values, which is the best way to serialize C# decimal values since using Double can result in loss of precision, which can be particularly problematic with financial data.

    You can find information on how to do this here: How to use decimal type in MongoDB