简体   繁体   English

Mongodb和MapReduce-结果丢失

[英]Mongodb and MapReduce - results missing

with this code: 使用此代码:

var map = function(){

    emit(1, { read: this.read, important: this.important, count: 1 })
}

var reduce = function(key, vals) {

    var i = 0, r = 0, c = 0;

    vals.forEach(function(d) {
       r += !d.read ? 0 : 1;
       i += d.important ? 0 : 1
       c += d.count;
    });

    return { read: r, important: i, count: c }
}

db.ipdr.mapReduce(map, reduce, { out: "__mr_test", verbose: true, query: { liid: "40001" } });
db.getCollection("__mr_test").find();

I get incomplete count: 我得到的计数不完整:

{
    "_id" : 1,
    "value" : {
        "read" : 1,
        "important" : 7,
        "count" : 7607
    }
}

"count" is OK, but "read" and "important" should be a lot higher. “计数”是可以的,但是“读取”和“重要”应该更高。 Am I missing something? 我想念什么吗?

Instead of 代替

r += !d.read ? 0 : 1;
i += d.important ? 0 : 1
c += d.count;

Shouldn't you be having 你不应该有

r += !d.read ? 0 : d.read;
i += d.important ? 0 : 1
c += d.count;

This is not a good usage of mapReduce. 这不是mapReduce的好用法。 The aggregation framework uses native code which is much faster than JavaScript execution and can do the same job. 聚合框架使用本机代码,该本机代码比JavaScript执行速度快得多,并且可以完成相同的工作。 Assuming "read" and "important" are logical values that is: 假设“读取”和“重要”是逻辑值,即:

db.posts.aggregate([
    { "$sort": { "read": 1, "important": 1 } },
    { "$group": {
        "_id": null,
        "read": { "$sum": { "$cond": [ "$read", 1, 0 ] } },
        "important": { "$sum": { "$cond": [ "$important", 1, 0 ] } },
        "count": { "$sum": 1 }
    }}
])

So not only faster but much more simple to code. 因此,不仅速度更快,而且编码更简单。

Given the sample documents: 给定样本文件:

{ "read" : true,  "important" : false }
{ "read" : true,  "important" : false }
{ "read" : false, "important" : false }
{ "read" : false, "important" : true  }
{ "read" : true,  "important" : true  }

The result would be: 结果将是:

{ "_id" : null, "read" : 3, "important" : 2, "count" : 5 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM