Behaviour of NumberLong in Mongo Shell

3.8k views Asked by At

I wrote the following 4 statements in the Mongo Shell

i) NumberLong(3)

ii) NumberLong(3)+NumberLong(4)

iii) typeof NumberLong(3)

iv) typeof (NumberLong(3)+NumberLong(4))

and their corresponding outputs were

i) NumberLong(3)

ii) 7

iii) object

iv) number

Although the second result makes the fourth one obvious, I am not able to get to the head or tail of this behaviour.What is happening behind the scenes?? I tried finding the underlying concept in the MongoDB documentation but couldn't find much. Please Help!!

1

There are 1 answers

1
Stennie On BEST ANSWER

What's the difference between Number and NumberLong?

JavaScript currently only has a single numeric type which is Number, represented as an IEEE 754 double-precision floating point value (8 bytes).

MongoDB's BSON storage representation has more numeric types than JavaScript, including 32-bit signed integers (4 bytes) and 64-bit signed integers (8 bytes).

The NumberInt() and NumberLong() constructors are data types in the mongo shell that allow you to create integer values rather than using JavaScript's default floating point number. These are implemented as custom prototypes so the typeof these will be object (as opposed to number which is part of the JavaScript primitive types).

When you add NumberLong() or NumberInt() values together, JavaScript coerces the result into the native number type which is why your results in the 2nd and 4th test differ from the 1st and 3rd.

Why use NumberLong / NumberInt?

These types are used to provide an interface to MongoDB's underlying BSON storage format.

A 32-bit integer (NumberInt) can be represented in half the bytes as compared to a Number or NumberLong.

A 64-bit integer (NumberLong) has more precision for large integer values as compared to a Number. Since a double-precision floating point representation reserves some bits for the exponent, the largest Number that can be precisely stored is 253 versus 263-1 for a NumberLong.