簡體   English   中英

Mongodb和MapReduce-結果丟失

[英]Mongodb and MapReduce - results missing

使用此代碼:

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

“計數”是可以的,但是“讀取”和“重要”應該更高。 我想念什么嗎?

代替

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;

這不是mapReduce的好用法。 聚合框架使用本機代碼,該本機代碼比JavaScript執行速度快得多,並且可以完成相同的工作。 假設“讀取”和“重要”是邏輯值,即:

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 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM