What is the best type for a Number?

In MongodDB atlas there are a variety of options for picking a data type for a Number, however there is no generic Number option, unlike the ability to do so using mongoose to create the schema, so which would be best to use in MongoDB atlas?

Hey @Quozzo_Crozzy

How big of a number are you thinking?

I think mongoose stores the number as a Int-32 BSON

If you are looking at a large number then use 64-bit Int
If you are looking at financial data and need to be extremely precise then use the Decmial128 which is also a Mongoose type.

Hope this helps

As far as I know Mongoose does not natively support long and double data types. “number” is a “schema type”, it just for input validation…

It is same on Atlas, these types for input validation, unless you pick Decimal128, mongodb stores everything same way generic number.

1 Like

Assuming you are referring to Inserting documents using the Atlas UI, a Double is the equivalent BSON data type to choose for JavaScript’s generic Number type (a JavaScript Number uses the same 64-bit floating point representation as a BSON Double).

The Atlas user interface uses BSON data types for field selection since they have more granular numeric representation than JavaScript including Int32, Int64, Double, and Decimal128 types.

Typically you would choose the most appropriate data type for your use case. For example, if your values will fit in the range of 32-bit integers (Int32) these use 4 bytes of storage (plus BSON overhead) versus 8 bytes for a 64-bit value. For numeric values requiring precise floating point representation (like currency with fractional values), you would use Decimal128 (which uses 16 bytes).

If you want to validate document inserts/updates using JSON Schema validation, you can either match specific numeric types or use the number type alias to match any numeric representation while still getting the advantages of appropriate storage size and precision.

Mongoose builds on the extended BSON data type support provided by the official MongoDB Node.js driver & BSON library. The driver provides object wrappers such as Int32 and Decimal128 so extended data types can be created and used from client code where possible. The MongoDB server will save values using the BSON types indicated by the driver.

For one example of how this works in Node.js/Mongoose, see: A Node.js Perspective on MongoDB 3.4: Decimal Type.

Regards,
Stennie

1 Like