我正在 mongo 中尝试 map-reduce,并遇到了一个数值问题,这让我完全陷入困境。给定以下映射和归约函数:
var map = function(){
key = "awesome";
emit(key, {count: 1})
}
var reduce = function(key, values){
var result = {count: 0};
values.forEach(function(value) {
result.count += value.count;
});
result.countBy2 = result.count/2
// result.count = result.count/2
return result
}
给出逻辑
"results" : [
{
"_id" : "awesome",
"value" : {
"value" : {
"count" : 7696.0000000000000000,
"countBy2" : 3848.0000000000000000
}
},
取消顶部代码片段中的注释行会产生非常奇怪的输出
"results" : [
{
"_id" : "awesome",
"value" : {
"count" : 98.0000000000000000,
"countBy2" : 98.0000000000000000
}
},
为什么?
反转注释行以保持映射和化简命令的对象格式相同(关联?)。 。
// result.countBy2 = result.count/2
result.count = result.count/2
仍然给出意外的输出
"results" : [
{
"_id" : "awesome",
"value" : {
"count" : 98.0000000000000000
}
}
我错过了什么?
最佳答案
当您的 reduce
函数包含将 count
除以 2 的行时,它违反了您必须遵守的reduce 函数的幂等要求,如 docs 中所述。 :
the reduce function must be idempotent. Ensure that the following statement is true:
reduce( key, [ reduce(key, valuesArray) ] ) == reduce( key, valuesArray )
这基本上是说,您需要能够将一个 reduce
回调的输出作为输入反馈到另一个调用中,并使结果保持不变。
如果您想对 Map-Reduce 的输出执行最终处理,那么您可以包含 finalize选项中的函数只会被调用一次。根据您最终想要执行的操作,您可能应该将计数除以 2:
finalize: function(key, reducedValue) { return { count: reducedValue.count/2 }; }
关于javascript - MongoDB 中的reduce 函数出现奇怪的数值错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32590807/