MongoDB MapReduce (original) (raw)

MongoDB Map-Reduce

Last Updated : 5 May, 2026

Map-Reduce is an older feature in MongoDB and is generally replaced by the aggregation pipeline for better performance and flexibility.

Syntax

db.collection.mapReduce(
mapFunction,
reduceFunction,
{
query: ,
out:
}
)

Steps to use Map Reduce in MongoDB

Let's try to understand the mapReduce() using the following example. In this example, we have five records from which we need to take out the maximum marks of each section and the keys are id, sec, marks.

{"id":1, "sec":"A", "marks":80}
{"id":2, "sec":"A", "marks":90}
{"id":1, "sec":"B", "marks":99}
{"id":1, "sec":"B", "marks":95}
{"id":1, "sec":"C", "marks":90}

Step 1: Define the map function

Group by sec and emit marks as values.

var map = function () {
emit(this.sec, this.marks);
}

Step 2: Define the Reduce Function

Compute the maximum marks for each section.

var reduce = function (sec, marks) {
return Array.max(marks)
}

Step 3: Run Map-Reduce

Store results in a new collection.

db.collectionName.mapReduce(map, reduce, { out: "collectionName" })

Step 4: View Result

db.collectionName.find()

**Output:

{"_id":"A", value:90}
{"_id":"B", value:99}
{"_id":"C", value:90}

Examples of MongoDB Map Reduce

The collection contains employee details like age and rank.

databsereducemap

Example 1: Find the Sum of Ranks Grouped by Ages

Calculate the sum of rank present inside the particular age group. Now age is our key on which we will perform group by (like in MySQL) and rank will be the key on which we will perform sum aggregation.

var map=function(){ emit(this.age,this.rank)};
var reduce=function(age,rank){ return Array.sum(rank);};
db.employee.mapReduce(map,reduce,{out :"resultCollection1"});

**Output:

Example 2: Performing avg() Aggregation on Rank Grouped by Ages

Calculate the average of the ranks grouped by age.

var map=function(){ emit(this.age,this.rank)};
var reduce=function(age,rank){ return Array.avg(rank);};
db.employee.mapReduce(map,reduce,{out :"resultCollection3"});
db.resultCollection3.find()

**Output:

Usage of Map-Reduce in MongoDB

Here are some usage of Map-Reduce:

Limitations of MongoDB Map-Reduce

While MongoDB Map-Reduce is powerful, it is not always the best option. Avoid using it when: