MongoDB map reduce使用嵌套对象



我正在运行一个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;
};

现在当我运行map reduce:

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
        }
}

如何输出更复杂的对象?

不能在map和reduce之间更改值的格式。

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

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

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

试试这个:

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);
});

相关内容

  • 没有找到相关文章

最新更新