我正在运行 map reduce 操作并以错误的数据结束。这是我的 map 和 reduce 函数:
var map_analytics = function() {
var key = this.owner;
if (this.apikey == null) {
var value = {api_call_with_key: 0, api_call_without_key: 1};
} else {
var value = {api_call_with_key: 1, api_call_without_key: 0};
}
emit(key, value);
};
var reduce_analytics = function(key_owner, api_calls) {
today = new Date();
firstofmonth = new Date(today.getFullYear(), today.getMonth(), 1);
reduced_val = {period: firstofmonth, analytics: {api_call_with_key: 0, api_call_without_key: 0}};
api_calls.forEach(function(value) {
reduced_val.analytics.api_call_with_key += value.api_call_with_key;
reduced_val.analytics.api_call_without_key += value.api_call_without_key;
});
return reduced_val;
};
现在当我运行我的地图减少时:
db.statistics.mapReduce(map_analytics, reduce_analytics, {out: { reduce: "analytics" }, query: { request_date: { $gte: firstofmonth}}})
我明白了:
{
"_id" : ObjectId("5136d880136b961c98c9a62f"),
"value" : {
"period" : ISODate("2013-05-01T06:00:00Z"),
"analytics" : {
"api_call_with_key" : NaN,
"api_call_without_key" : NaN
}
}
}
知道为什么我得到 NaN 而不是实际值吗?
一个更简单的版本可以工作:
var reduce_analytics = function(key_owner, api_calls) {
reduced_val = {api_call_with_key: 0, api_call_without_key: 0};
api_calls.forEach(function(value) {
reduced_val.api_call_with_key += value.api_call_with_key;
reduced_val.api_call_without_key += value.api_call_without_key;
});
return reduced_val;
};
并生产
{
"_id" : ObjectId("5143b2c8136b9616343dacec"),
"value" : {
"api_call_with_key" : 0,
"api_call_without_key" : 2,
"total_api_calls" : 2
}
}
如何输出更复杂的对象?