Skip to content
Jon Clausen edited this page Dec 21, 2015 · 3 revisions

Map-Reduce

Map-Reduce functionality expands aggregation by allowing you to use javascript to return customized results.

Using the people collection, again, let's perform the same aggregation function using Map-Reduce:

//We'll need our db collection object again
var Collection = people.getDBInstance();
//Define our mapping function, which emits the records we will reduce
var map="
	function(){
		if(this.city === 'Grand Rapids' && this.state === 'Michigan') emit(this._id,this.iteration)
	}
";

//Define our reduction of those mapped records, which duplicates our aggregation functionality and key names
var reduce = "
	function(key,iterations){
	    var groupedZipCodes = [];
		for (var i in iterations){
			var existing = groupZipCodes.find(function (d) {
			    return d.postalcode === iterations[i].postalcode;
			});
			if(typeof(existing === 'undefined')){
				groupedZipCodes.push({"_id":iterations[i].postalcode,"count":1});	
			} else {
				//we can modify this by reference
				existing.count++;
			}
		} 
		return groupedZipCodes;
	}
";

//Finally Run our query, which will produce the same result as aggregate()
var reduction = Collection.mapReduce(map,reduce);

Once again, we'll get back:

[
	{
		"_id":49503,
		"count":25
	},
	{
		"_id":49506,
		"count":15
	},
	{
		"_id":49512,
		"count":1
	}
]

For more information on how to use Map-Reduce, see Mongo's documentation examples.