Mongodb和MapReduce-缺少结果

Mongodb and MapReduce - results missing

本文关键字:结果 MapReduce- Mongodb      更新时间:2023-09-26

使用以下代码:

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

我得到不完整的计数:

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

"count"可以,但"read"answers"important"应该高得多。我是不是错过了什么?

这不是mapReduce的好用法。聚合框架使用的本地代码比JavaScript执行速度快得多,可以完成同样的工作。假设"读取"answers"重要"是逻辑值,即:

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

因此,不仅速度更快,而且代码更简单。

给定样本文件:

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

结果是:

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

而不是

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

你不应该有吗

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