Mongodb c# driver BsonDocument.Parse(stringjson) doesnt convert decimal values with decimal128 type, it takes them as double

The MongoDB.Driver 2.11.x BsonDocument.Parse(stringjson) not converting decimal types in json to decimal128. It always takes it as double.
e.g. json string
{
“bigdecimal”:123456789123456789123456789.23
}

After applying BsonDocument.Parse() the result is as follows:
How can we specify that the certain value is of decimal128 type. Tried the same with BsonSerializer.Deserialize as well, same result.

BsonDocument’s bigdecimal element:

1 Like

Hello @Shabbir_Lathsaheb, welcome to the MongoDB Community forum!

In MongoDB, by default a number is of type double. That is the reason when you parse the JSON string with a field’s value as a number it is showing as a double. That is the expected behavior. You need to explicitly convert the number to the decimal128 type.

An example, using C# driver API:

var json = "{ 'bigdecimal': 123456789123456789123456789.23 }";
var bson = BsonDocument.Parse(json);
Console.WriteLine(bson.GetValue("bigdecimal").BsonType); // prints Double

// Convert the field to decimal128 type
var decNum = bson.GetValue("bigdecimal").ToDecimal128();
Console.WriteLine(decNum.GetType()); // prints MongoDB.Bson.Decimal128

// Set the element value
bson.Set("bigdecimal", decNum);

@Prasad_Saya : Thanks for the reply. However, from the json string we cant know which property is of which type. We don’t have schema defined. Like json parser has ability to accept a setting to consider all float as decimal. Can bson parser not have same user defined settings, since its a conflict?

@Shabbir_Lathsaheb, I don’t know of any feature which detects a data type and converts as per your requirement. I think, you may have to build the functionality as per your application needs.

Generally, the MongoDB collection document is mapped to a user defined class in C#. The class can have some functionality to convert to and from the desired data type for specific fields. Applications generally have some structure to their data - that is how various components of the application use the data - from database layer to application layer to user interface layer. These layers have their own ways and methods of data representations and conversions are required, sometimes - as in this case.

Having data without some schema specification is your application and then you need to improvise. I don’t have further suggestions regarding this.

1 Like