根据条件在MapReduce中对文档进行计数-MongoDB [英] Counting documents in MapReduce depending on condition - MongoDB

查看:69
本文介绍了根据条件在MapReduce中对文档进行计数-MongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Map Reduce根据每个日期的字段值之一对文档数量进行计数.首先,这是几个常规find()函数的结果:

I am trying to use a Map Reduce to count number documents according to one of the field values per date. First, here are the results from a couple of regular find() functions:

db.errors.find({ "cDate" : ISODate("2012-11-20T00:00:00Z") }).count();

返回 579(即该日期有 579 个文档)

returns 579 (ie. there are 579 documents for this date)

db.errors.find( { $and: [ { "cDate" : ISODate("2012-11-20T00:00:00Z") }, {"Type":"General"} ] } ).count()

返回443(即,该日期有443个文档,其中Type ="General")

returns 443 (ie. there are 443 documents for this date where Type="General")

以下是我的MapReduce:

Following is my MapReduce:

db.runCommand({ mapreduce: "errors", 
 map : function Map() {
    emit(
        this.cDate,//Holds a date value
        {
        count: 1,
        countGeneral: 1,
        Type: this.Type 
        }
    );
},

reduce : function Reduce(key, values) {
    var reduced = {count:0,countGeneral:0,Type:''};

    values.forEach(function(val) {
        reduced.count += val.count; 
        if (val.Type === 'General')
            reduced.countGeneral += val.countGeneral;
    });

return reduced; 
},

finalize : function Finalize(key, reduced) {
    return reduced;
},

query : { "cDate" : { "$gte" : ISODate("2012-11-20T00:00:00Z") } },

out : { inline : 1 }
});

对于日期20-11-20,地图减少收益:

For the date 20-11-20 the map reduce returns:

count: 579

countGeneral: 60 (should be 443 according to the above find query)

现在,我知道Reduce的循环方式是不可预测的,那么我该怎么做?谢谢

Now, I understand that the Reduce is unpredictable in the way it loops so how should I do this? Thanks

推荐答案

您的地图功能不正确.您可以执行以下操作:

Your map function is wrong. You could do something like this:

function Map() {
    var cG=0;
    if (this.Type == 'General') { cG=1; }
    emit(
        this.cDate,//Holds a date value
        {
        count: 1,
        countGeneral: cG
        }
    );
}

如果Type为'General',则发出countGeneral 1,否则为0.

This emits countGeneral 1 if Type is 'General' and 0 otherwise.

然后,您可以将所有类型检查从您的emit函数中完全删除,因为无论如何您都要在reduce函数中销毁它.当前,您的reduce clobbers类型信息在reduce阶段从emit传递过来.

Then you can remove the type check from your emit function entirely, since you're destroying it anyway in your reduce function. Currently your reduce clobbers Type information passed from emit during the reduce phase.

这篇关于根据条件在MapReduce中对文档进行计数-MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆