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!!
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()
andNumberLong()
constructors are data types in themongo
shell that allow you to create integer values rather than using JavaScript's default floating point number. These are implemented as custom prototypes so thetypeof
these will beobject
(as opposed tonumber
which is part of the JavaScript primitive types).When you add
NumberLong()
orNumberInt()
values together, JavaScript coerces the result into the nativenumber
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 aNumber
orNumberLong
.A 64-bit integer (
NumberLong
) has more precision for large integer values as compared to aNumber
. Since a double-precision floating point representation reserves some bits for the exponent, the largestNumber
that can be precisely stored is 253 versus 263-1 for aNumberLong
.