Created
October 22, 2016 05:18
-
-
Save rohitbishnoi/3bdc215412a931e9de4dc0fa716eaaa5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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