Long accumulator instead of Double in MongoDB group() function

廉价感情. 提交于 2019-12-11 03:00:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!