从mongoDB map中访问输出reduce

时间:2012-10-01 18:58:47

标签: mongodb mapreduce

如何从以下mongoDB map reduce代码访问输出?我假设map reduce函数正在生成一个名为'session_stat'的集合,其中包含:'dayOfWeek'和'count',我可以使用find()和printValue函数进行打印。但是当我使用'mongo code.js'执行代码时,我只是得到“未定义”。提前谢谢。

db = db.getSiblingDB("mrex");

// simulate saving records that log the lengths of user sessions in seconds                                                                                                                                                                                                                                                                                                 
db.session.save({userid:"a", time: ISODate('2011-11-03 14:17:00'), length: 95});
db.session.save({userid:"b", time: ISODate('2011-11-03 14:23:00'), length: 110});
db.session.save({userid:"c", time: ISODate('2011-11-03 15:02:00'), length: 120});
db.session.save({userid:"d", time: ISODate('2011-11-03 16:45:00'), length: 45});

function mapf()
{
    emit(this.time.getDay(),
     {count:1});
}

function reducef(key, values)
{
    var r = {dayOfWeek:key, count:0};
    values.forEach(function(v)
               {
                   r.count += v.count;
               });
    return r;
}

var mrcom1 = db.runCommand( { mapreduce:"session",
                          map:mapf,
                          reduce:reducef,
                          query: {time: {$gt:ISODate('2011-11-03 00:00:00')}},
                          out: { reduce: "session_stat" }
});

function printValue (r) {
    print(r.count)
};

db.session_stat.find().forEach(printValue)

1 个答案:

答案 0 :(得分:1)

MongoDB的map-reduce命令生成一组文档,其中包含名为“value”的字段,其中包含reduce返回值。您需要进入此字段才能找到您的子文档。

使用它作为printValue函数:

function printValue (r) {
    print(r.value.count)
};