TaijaQ
6/28/2017 - 10:48 AM

From http://mongoosejs.com/docs/api.html#model_Model.mapReduce

var Foo = new Schema({
    type:        : String
  , date         : { type: Date, default: Date.now }
  , value        : Number
});

Foo.statics.countValueForDate = function(start, end, callback) {
  var mapFunction = function() {
    emit(this.type, { count: this.value } )
  }
  var reduceFunction = function(key, values) {
    var result = { count: 0 };
    values.forEach(function(value) {
      result.count += value.count;
     });
    return result;
  }
  this.collection.mapReduce(
    mapFunction.toString(),
    reduceFunction.toString(),
    { query: { date: { $gte: start }, date: { $lte: end } }, out: { inline: 1 } },
    callback
  );
}
var o = {};
o.map = function () { emit(this.name, 1) }
o.reduce = function (k, vals) { return vals.length }
o.out = { replace: 'createdCollectionNameForResults' }
o.verbose = true;

User.mapReduce(o, function (err, model, stats) {
  console.log('map reduce took %d ms', stats.processtime)
  model.find().where('value').gt(10).exec(function (err, docs) {
    console.log(docs);
  });
})

// `mapReduce()` returns a promise. However, ES6 promises can only
// resolve to exactly one value,
o.resolveToObject = true;
var promise = User.mapReduce(o);
promise.then(function (res) {
  var model = res.model;
  var stats = res.stats;
  console.log('map reduce took %d ms', stats.processtime)
  return model.find().where('value').gt(10).exec();
}).then(function (docs) {
   console.log(docs);
}).then(null, handleError).end()
//mongo shell code

mapper = function () {
emit(this.gender, 1);
};
reducer = function(gender, count){
return Array.sum(count);
};
db.sourceData.mapReduce(
mapper,
reducer,
{
out : "example1_results"
}
);
db.example1_results.find()

mapper = function () {
	emit(this.gender, 1);
};
 
reducer = function(gender, count){
 	return Array.sum(count);
};
 
db.sourceData.mapReduce(
	mapper,
	reducer,
	{
		out : "example1_results"
	}
 );
 
 db.example1_results.find()
//Example 4 : Count the number of users in each hobby

var mongojs = require('mongojs');
var db = mongojs('mapReduceDB', ['sourceData', 'example3_results']);
 
var mapper = function () {
	 var hobbys = this.hobbies.split(',');
	  for (i in hobbys) {
        emit(hobbys[i], 1);
    }
};
 
var reducer = function (key, values) {
	var count = 0;
    for (index in values) {
        count += values[index];
    }
 
    return count;
};
 
 
db.sourceData.mapReduce(
	mapper,
	reducer,
	{
		out : "example3_results"
	}
 );
 
 db.example3_results.find(function (err, docs) {
 	if(err) console.log(err);
 	console.log(docs);
 });
// Example 3 : Get the Eldest and Youngest Person in each gender

var mongojs = require('mongojs');
var db = mongojs('mapReduceDB', ['sourceData', 'example2_results']);
 
 
var mapper = function () {
	var x = {age : this.age, name : this.name};
	emit(this.gender, {min : x , max : x});
};
 
 
var reducer = function(key, values){
 	var res = values[0];
 	for (var i = 1; i < values.length; i++) {
 		if(values[i].min.age < res.min.age)
 			res.min = {name : values[i].min.name, age : values[i].min.age};
        if (values[i].max.age > res.max.age) 
           res.max = {name : values[i].max.name, age : values[i].max.age};
 	};
 	return res;
};

db.sourceData.mapReduce(
	mapper,
	reducer,
	{
		out : "example2_results"
	}
 );
 
 db.example2_results.find(function (err, docs) {
 	if(err) console.log(err);
 	console.log(JSON.stringify(docs));
 });