Search code examples
c#mongodbswagger

Unable to cast object of type 'MongoDB.Bson.BsonDecimal128' to type 'MongoDB.Bson.BsonBoolean'


I had an issue with sorting my collection by a decimal value that I've inserted into a MongoDB database with the decimal type.

Shortly after I've realized that the MongoDB driver converted the value wrong; in the database the value gets falsely converted into a string and that's why the sorting doesn't work.

So, I've tried using the BsonDecimal128 type to insert it into the database. That works perfectly in the database and shows as a Decimal128! The sorting also worked correctly when testing it out in MongoDBCompass.

But, once I tried to connect to the Swagger UI to test the shell queries, it freezes and there's a browser popup saying that the page is slowing down my browser. That hasn't happened before. Image of the browser error

When I try it via the URL I get the error message InvalidCastException: Unable to cast object of type 'MongoDB.Bson.BsonDecimal128' to type 'MongoDB.Bson.BsonBoolean'.

How do I fix this?


Solution

  • Okay, so I found a workaround. I converted the calculated decimal value into a double and it seems to do the trick:

    Value = Convert.ToDouble(value)
    

    It's better to avoid decimal as long as double works too.