Skip to content
Advertisement

How to new a NumberDecimal() in JavaScript Mongodb?

I tried to run some Javascript NumberDecimal tests in Mongodb3.4, but however the output is never correct, if I used the NumberInt instead, then the result is correct. Does Javascript unsupports NumberDecimal type?

The following is my testing script:

    var X=new NumberDecimal("100");
    var Y=new NumberDecimal("100");
    var RTNEqual=(X.valueOf()==Y.valueOf());
    var RTNPlus=X+Y;
    print("Equal=>" + RTNEqual + "  RTNPlus=>" + RTNPlus)

    Output: 
    Equal=>false  RTNPlus=>NumberDecimal("100")NumberDecimal("100")

Thank you~

Advertisement

Answer

The mongo shell (as at 3.4.5) does not support arithmetic with NumberDecimal values. The decimal type is not native to JavaScript, so decimal values in the shell are strings representing the BSON value stored in MongoDB.

As per discussion on SERVER-19676 in the MongoDB issue tracker:

Due to the fundamental problems inherent to doing non-floating point math in javascript, there isn’t any easy system to hook into to provide arithmetic support for our types. If/when javascript provides operator overloading, or something that looks more live value types, we may revisit the issue. In the meantime, we aren’t planning on re-implementing arithmetic via methods.

However, decimal values are fully supported if you manipulate on the server via the aggregation framework:

var X=new NumberDecimal("100");
var Y=new NumberDecimal("100");

db.omnum.aggregate(
    { $project: {
        _id: 0,
        RTNEqual: { $eq: [X, Y] },
        RTNPlus: { $sum: [X, Y] }
    }}
)

Output:

{
  "result": [
    {
      "RTNEqual": true,
      "RTNPlus": NumberDecimal("200")
    }
  ],
  "ok": 1
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement