【问题标题】:Map reduce to count the unique count映射减少以计算唯一计数
【发布时间】:2015-02-06 11:58:36
【问题描述】:

我想要一个 map reduce 函数从满足以下条件的以下输入集合中绘制以下输出。

输入集合:

[{

    a:1,
    b:'test',
    indices:[1,2,4,5]
}, {
    a:2,
    b:'test',
    indices:[2, 3, 5]
}, {
    a:2,
    b:'test',
    indices:[1, 2, 4]
}, {
    a:3,
    b:'apple',
    indices:[1, 2]
}, {
    a:4,
    b:'apple',
    indices:[1, 3, 5]
}, {
    a:5,
    b:'orange',
    indices:[232]
}, {
    a:5,
    b:'dummy',
    indices:[2]
}, {
    a:6,
    b:'dummy',
    indices:[11, 2, 4]
}, {
    a:6,
    b:'dummy',
    indices:[11, 3, 2]
}, {
    a:6,
    b:'dummy',
    indices:[1, 2, 3, 4, 5]
}]

条件是:

  1. 只选择索引数组有2。这可以发送为 询问。即查询:{indices:{$in:2}}
  2. b分组
  3. 如果有重复的a,那么它应该被认为是1 例如:具有a = 2的文档存在两次满足条件索引 有 2 个。
  4. 我的输入集合总是满足条件 if a 存在于“测试”中,它不会出现在dummy/apple/etc 中。但是一个 可以重复。

这是我尝试过的:

db.x.mapReduce(function(){
        emit(this.b, 1);
    }, function(key, reducable){
        return Array.sum(reducable);
    }, {
    out: {inline: 1},
    query:{
        'indices':{$in:2}
    }
    });

输出: [

{
    "_id" : test",
    "value" : {
        "count" : 3 -> It should be 2
    }
},{
    "_id" : apple",
    "value" : {
        "count" : 2
    }
},{
    "_id" : dummy",
    "value" : {
        "count" : 4 -> It should be 2
    }
}]

预期输出:

[{
    "_id" : test",
    "value" : {
        "count" : 2
    }
},{
    "_id" : apple",
    "value" : {
        "count" : 2
    }
},{
    "_id" : dummy",
    "value" : {
        "count" : 2
    }
}]

【问题讨论】:

    标签: mongodb mapreduce mongodb-query aggregation-framework


    【解决方案1】:

    不需要 map/reduce。使用聚合:

    > db.crawler_status.aggregate([
        { "$match" : { "indices" : 2 } },
        { "$group" : { "_id" : { "b" : "$b", "a" : "$a" } } },
        { "$group" : { "_id" : "$_id.b", "count" : { "$sum" : 1 } } }
    ])
    { "_id" : "test", "count" : 2 }
    { "_id" : "apple", "count" : 1 }    // your sample output was mistaken
    { "_id" : "dummy", "count" : 2 }
    

    【讨论】:

      猜你喜欢
      • 2017-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-02
      • 2016-06-06
      • 2012-03-09
      相关资源
      最近更新 更多