Does MongoDB's Map/Reduce always return results in floats?
I am using Mongoid, which is on top of the Ruby MongDB driver. Even though my M开发者_如何学运维ap's emit is giving out a parseInt(num)
, and the Reduce's return is giving back also a parseInt(num)
, the final results still are floats.
Is that particular to MongoDB? Any way to make it integer instead?
The parseInt
function officially takes a string as parameter. This string is parsed as if it were an integer, thus ignoring everything after the first non-numeric character. If you provide a floating point number, it will be converted to a string before it is parsed.
The parseInt
functions returns a Number
, not an integer. Number
is the only numeric data type in JavaScript; there is no distinction between integers and floats.
So while parseInt
will remove any decimals, the data type doesn't change. Therefore Mongoid doesn't know whether to treat the result as a float or an integer. You're responsible for converting the result to an integer, as you can see in this example.
Update
I came across the NumberLong
type, which represents a 64-bit integer. If you return new NumberLong(num)
from your reduce function, Mongoid may treat it as an integer type.
Note that you'll need MongoDB 1.6 for this to work in the MongoDB Shell. I don't know whether Mongoid supports it yet.
精彩评论