map() function: Uses emit(key, value) where the key is used for grouping (similar to Group By in MySQL).
reduce() function:Aggregate values for each key (e.g., sum, avg).
query: Filters the input documents before processing.
out: Specifies the collection where the result will be stored.
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.
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"});
In map(), emit(this.age, this.rank) groups documents by age and emits rank for aggregation.
In reduce(), Array.sum(rank) aggregates ranks per age.
The { out: "resultCollection1" } option saves the result in the specified collection.
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()