javascript - 如何使用 MapReduce 和 Aggregate 进行相同的分析

标签 javascript mongodb mapreduce aggregation-framework

我需要使用mapReduce 和/或聚合进行此分析:

DBCollection coll = db.getCollection("documents");
DBCursor cursor = coll.find();
Map<String,Integer> map = new HashMap<String,Integer>();
while(cursor.hasNext()){
    DBObject obj = cursor.next();
    BasicDBList list = (BasicDBList)obj.get("cats");
    for(int i=0;i<list.size();i++){
        String cat = list.get(i).toString();
        int hits   = 0;
        if(map.containsKey(cat)){
            hits = map.get(cat);
        }
        hits++;
        map.put(cat, hits);
    }
}

有人能给我一个关于如何使用 mapReduce 和聚合来实现我需要的正确示例吗?

谢谢!

最佳答案

您似乎正在计算数组中元素的唯一出现次数。无论内容是什么并不重要,因为您只是将其转换为 map 中的字符串键。但这是一个示例:

{ "cats" : [ 1, 2, 3, 4, 5 ] }
{ "cats" : [ 2, 4 ] }
{ "cats" : [ 1, 5 ] }
{ "cats" : [ 4, 5 ] }

聚合框架是最快的:

db.cats.aggregate([
    { "$unwind": "$cats" },
    { "$group": {
        "_id": "$cats",
        "count": { "$sum": 1 }
    }}
])

产生:

{ "_id" : 5, "count" : 3 }
{ "_id" : 4, "count" : 3 }
{ "_id" : 3, "count" : 1 }
{ "_id" : 2, "count" : 2 }
{ "_id" : 1, "count" : 2 }

Map reduce 大致相同,但速度较慢:

db.cats.mapreduce(
    function() {
        this.cats.forEach(function(cat) {
            emit( cat, 1 );
        });
    },
    function(key,values) {
        return Array.sum( values );
    },
    { "out": { "inline": 1 } }
)

关于javascript - 如何使用 MapReduce 和 Aggregate 进行相同的分析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25200318/

相关文章:

hadoop - 使用 ArrayWritables 时出现问题

javascript - 如何在更改事件中自行提交 web2py 组件

javascript - Three.js ply loader - 对象未正确渲染

javascript - requestAnimationFrame JavaScript : Constant Frame Rate/Smooth Graphics

javascript - 通过 Promise 将 Node js 连接到 Mongo Atlas

java - 如何通过 MapReduce 的第二个选项卡拆分单词?

javascript - 从 ascx 代码隐藏文件调用 Aspx javascript 函数

grails - Grails + MongoDB:isNull条件的替代品是什么?

ruby-on-rails - 使用 Mongoid 的货币数据类型

java - 在不创建 jar 文件的情况下运行 hadoop 作业