views:

30

answers:

1

I am using Mongoid, which is on top of the Ruby MongDB driver. Even though my Map'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?

+2  A: 

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.

Niels van der Rest
so in MongoDB Shell or in Firefox, if it is `parseInt('1') + parseInt('123')`, then `124` is returned, not 124.0. Where in MongoDB is it triggered to have `.0` added to the end? I can even make it so by `123 * 1.0` or `123 + 1.0`
動靜能量
@Jian Lin: MongoDB doesn't 'add' `.0`, but Mongoid represents it that way. Mongoid only knows that it's a `Number`, but it can't tell whether it's an integer or float. See my updated answer for a possible alternative.
Niels van der Rest