MongoDB map使用嵌套对象进行缩减

时间:2013-05-08 04:37:05

标签: javascript mongodb mapreduce

我正在运行地图缩减操作并最终导致错误数据。这是我的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
        }
}

如何输出更复杂的对象?

2 个答案:

答案 0 :(得分:1)

您无法在map和reduce之间更改值的格式。

换句话说,当你的地图发出(键,VALUE)时,你的reduce函数必须返回相同的格式VALUE。

因此,如果您希望将日期作为值的一部分,则需要在映射阶段将其置入。如果按密钥分组,日期则应该是密钥文档的一部分。

此外,如果可以的话,我建议使用聚合框架 - 它比map-reduce快得多。

答案 1 :(得分:0)

试试这个:

api_calls.forEach(function(value) {
    reduced_val.analytics.api_call_with_key += Number(value.api_call_with_key);
    reduced_val.analytics.api_call_without_key += Number(value.api_call_without_key);
});