Databases Reference
In-Depth Information
Numbers
JavaScript has one “number” type. Because MongoDB has three number types (4-byte
integer, 8-byte integer, and 8-byte float), the shell has to hack around JavaScript's lim-
itations a bit. By default, any number in the shell is treated as a double by MongoDB.
This means that if you retrieve a 4-byte integer from the database, manipulate its docu-
ment, and save it back to the database even without changing the integer , the integer
will be resaved as a floating-point number. Thus, it is generally a good idea not to
overwrite entire documents from the shell (see Chapter 3 for information on making
changes to the values of individual keys).
Another problem with every number being represented by a double is that there are
some 8-byte integers that cannot be accurately represented by 8-byte floats. Therefore,
if you save an 8-byte integer and look at it in the shell, the shell will display it as an
embedded document indicating that it might not be exact. For example, if we save a
document with a "myInteger" key whose value is the 64-bit integer, 3 , and then look at
it in the shell, it will look like this:
> doc = db.nums.findOne()
{
"_id" : ObjectId("4c0beecfd096a2580fe6fa08"),
"myInteger" : {
"floatApprox" : 3
}
}
The number is not changed in the database (unless you modify and resave the object
from the shell, in which case it will turn into a float); the embedded document just
indicates that the shell is displaying a floating-point approximation of an 8-byte integer.
If this embedded document has only one key, it is, in fact, exact.
If you insert an 8-byte integer that cannot be accurately displayed as a double, the shell
will add two keys, "top" and "bottom" , containing the 32-bit integers representing the
4 high-order bytes and 4 low-order bytes of the integer, respectively. For instance, if
we insert 9223372036854775807 , the shell will show us the following:
> db.nums.findOne()
{
"_id" : ObjectId("4c0beecfd096a2580fe6fa09"),
"myInteger" : {
"floatApprox" : 9223372036854776000,
"top" : 2147483647,
"bottom" : 4294967295
}
}
The "floatApprox" embedded documents are special and can be manipulated as num-
bers as well as documents:
> doc.myInteger + 1
4
 
Search WWH ::




Custom Search