mongodb(map-reduce)

下例中给出mongoose的一个mapreduce例子,参考mongoose官网。

基本概念:

Map函数
接受一个键值对(key-value pair),产生一组中间键值对。MapReduce框架会将map函数产生的中间键值对里键相同的值传递给一个reduce函数。
Reduce函数
接受一个键,以及相关的一组值,将这组值进行合并产生一组规模更小的值(通常只有一个或零个值)。
 
  • 定义一个collection:
var user    = new Schema({    
    username:{type:String}, 
    
    password:{type:String},
})
  • mapreduce:
exports.test = function(){    
    var user = require('../dao/user');
    var model = user.model;
    
    var option = {};
    //输出为_id:name, value:1
    option.map = function () { emit(this.username, 1) }
    //将键值相同的传给同一个reduce函数,此时k为_id:name, vals 为value的数组
    //当不存在多个键值对时,该reduce函数不会被调用
    option.reduce = function (k, vals) {
        return vals.length}
    model.mapReduce(o, function (err, results) {
      console.log(results)
    });
}
  • 输出结果:
//数据库中存有三条记录,一条用户名为hello,两条用户名为test
[ { _id: 'hello', value: 1 }, { _id: 'test', value: 2 } ]
原文地址:https://www.cnblogs.com/Fredric-2013/p/4445396.html