You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
1.6 KiB
1.6 KiB
Mongo - MapReduce
Lesson Objectives
- Explain what MapReduce is and why we have it
- Explain structure of Map Reduce
- Explain map function
- Explain reduce function
- Explain aggregating multiple values
- Explain Multiple group by
Explain what MapReduce is and why we have it
Explain structure of Map Reduce
- db.collectionName.mapReduce(mapFunction, reduceFunction, { query: {}, out:{} })
- out
- collection name
- { [ replace | inline | merge | reduce ]: 1 }
Explain map function
- return key=>value pair
var emitter = function (){
if(this.gender === 'm'){
emit(this.name, { yum : this.loves[0], weight:this.weight });
}
}
db.employees.mapReduce(emitter, function(){}, {out:'mapTest'});
Explain reduce function
- if multiple values for a key, how to reduce
var emitter = function (){
emit(this.gender, this.weight);
}
var reducer = function (key, values){
return Array.sum(values);
}
db.employees.mapReduce(emitter, reducer, {out:'mapTest'});
Multiple values
var emitter = function (){
emit(this.gender, { weights: this.weight, money: this.salary });
}
var reducer = function(key, values){
var total_weight = 0;
var total_salary = 0;
for(var i=0; i<values.length; i++){
total_weight += values[i].weights;
total_salary += values[i].money;
}
return {total_weight: total_weight, total_salary: total_salary}
}
db.employees.mapReduce(emitter, reducer, { out: 'mapTest' });
db.mapTest.find();
Multiple group by
var emitter = function (){
emit(
{
gender: this.gender,
weight: this.weight
},
this.weight
);
}