Skip to content

Instantly share code, notes, and snippets.

@rohitbishnoi
Created October 22, 2016 05:18
Show Gist options
  • Save rohitbishnoi/3bdc215412a931e9de4dc0fa716eaaa5 to your computer and use it in GitHub Desktop.
Save rohitbishnoi/3bdc215412a931e9de4dc0fa716eaaa5 to your computer and use it in GitHub Desktop.
//Calculate average age of the students
var mapFunction = function(){
emit("avgAge", this.age);
};
var reduceFunction = function(age, values){
return Array.sum(values) / values.length ;
};
db.student.mapReduce(mapFunction, reduceFunction, {out : {inline : 1}});
// using aggregate
db.student.aggregate([{$group: {_id: null, avgAge: {$avg: "$age"}}}])
// Correct answer
var mapFunction = function(){
emit("avgAge", {sum: this.age, count: 1});
};
var reduceFunction = function(age, values){
var sumOfAge = Array.sum(values.map(function(val){
return val.sum;
}));
var totalCount = Array.sum(values.map(function(val){
return val.count;
}));
return {sum: sumOfAge, count: totalCount};
};
var finalizeFunction = function(age, values){
return values.sum / values.count;
};
db.student.mapReduce(mapFunction, reduceFunction, {out : {inline : 1}, finalize : finalizeFunction});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment