问题
I am using MongoDB via official Java API. I can store and retrive Long values without any extra effort. But when I try to accumulate these values using group() function, JavaScript interpreter converts everything into Doubles and the final result ends up being a Double.
Here is my group command:
{
...
initial: { count: 0 },
reduce: "function (o, a) { a.count += o.count; }"
}
Is there a way to tell the interpreter that count is in fact a Long? Something like count: 0L or count: Long(0)? Or should I do the accumulation on Java side?
回答1:
This is because group command actually run map/reduce, and map/reduce is a javascript. In the javascript default number type is a double, because of this it return doubles.
So you can probably wrap your numbers with NumberLong(..) if you wanna see long in group command result:
{
...
initial: { count: new NumberLong(0) },
reduce: "function (o, a) { a.count += new NumberLong(o.count); }"
}
Not tested this, but almost sure that it should work.
来源:https://stackoverflow.com/questions/9314300/long-accumulator-instead-of-double-in-mongodb-group-function