.Net MongoDB.Driver 2.19.0 - Issue with decimal deserialization from BsonDocument

Hello!

I’m having issue with retrieving decimal values from MongoDb. Here is what I do:

I’m saving dictionary<string, object> as BsonDocument.

        var dict = new Dictionary<string, object>()
        {
            { "int", 1 },
            { "string", "1"},
            { "decimal", 1.1m },
            { "decimalList", new List<object> { 1.1m, 2.2m } },
            { "intDict", new Dictionary<string, object> { { "one", 1 }, { "two", 2 } } },
            { "stringDict", new Dictionary<string, object> { { "one", "1" }, { "two", "2" } } },
            { "decimalDict", new Dictionary<string, object> { { "one", 1.1m }, { "two", 3.6m } } }
        };

        var something = new Something
        {
            Parameters = new BsonDocument(dict)
        };

        // save to MongoDb

Here is a copy of the document which is stored in mongo:

{
  "_id": {
    "$oid": "64215cd5f3a0a301be2d13f2"
  },
  "parameters": {
    "int": 1,
    "string": "1",
    "decimal": {
      "$numberDecimal": "1.1"
    },
    "decimalList": [
      {
        "$numberDecimal": "1.1"
      },
      {
        "$numberDecimal": "2.2"
      }
    ],
    "intDict": {
      "one": 1,
      "two": 2
    },
    "stringDict": {
      "one": "1",
      "two": "2"
    },
    "decimalDict": {
      "one": {
        "$numberDecimal": "1.1"
      },
      "two": {
        "$numberDecimal": "3.6"
      }
    }
  }
}

The problem occurs when I retrieve data from MongoDb:

{ "int" : 1, "string" : "1", "decimal" : NumberDecimal("1.1"), "decimalList" : [NumberDecimal("1.1"), NumberDecimal("2.2")], "intDict" : { "one" : 1, "two" : 2 }, "stringDict" : { "one" : "1", "two" : "2" }, "decimalDict" : { "one" : NumberDecimal("1.1"), "two" : NumberDecimal("3.6") } }

And after converting BsonDocument back to dictionary I get decimals as Decimal128 type:

And final response from Api looks like:

{
  "int": 1,
  "string": "1",
  "decimal": {},
  "decimalList": [
    {},
    {}
  ],
  "intDict": {
    "one": 1,
    "two": 2
  },
  "stringDict": {
    "one": "1",
    "two": "2"
  },
  "decimalDict": {
    "one": {},
    "two": {}
  }
}

Am I doing something wrong?
Is it a bug in .Net MongoDB.Driver?

FYI JSON doesn’t support decimal as a data types, BSON will, JSON won’t, same with binary and Date data types.

You have to use a string to define decimal instead, and then it’ll work.

I understand MongoDB U will define BSON and JSON as the same thing, except JSON is more human readable, which is an extremely poor description between their differences.

The largest difference is that JSON does not support many datatypes that BSON does, and pending version of MongoDB the datatypes JSON supports are even impacted, such as MongoDB 5.0 allowing the use of $ for example, while other versions prior to 5.0 will not support $ in JSON.