Skip to content

Instantly share code, notes, and snippets.

@ceccode
Created October 14, 2014 08:18
Show Gist options
  • Select an option

  • Save ceccode/37de5358187ff867cb71 to your computer and use it in GitHub Desktop.

Select an option

Save ceccode/37de5358187ff867cb71 to your computer and use it in GitHub Desktop.
Get Avg of array using MongoDB MapReduce
db.avgexample.drop();
db.avgexample.insert({"name":"test1", "value": [1,2,3,4]});
db.avgexample.insert({"name":"test1", "value": [5,6,7,8]});
var map = function() {
var sum = 0;
var count = 0;
for (var i = 0; i < this.value.length; i++) {
sum = sum + this.value[i];
count = count + 1;
}
var o = {sum:sum,count:count};
emit(this.name, o);
};
var reduce = function(key, values) {
var a = values[0]; //Currently, the return value from a reduce function cannot be an array
for (var i=1; i < values.length; i++){
var b = values[i];
a.sum += b.sum;
a.count += b.count;
}
return a;
};
function finalize(key, value){
value.avg = value.sum / value.count;
return value;
}
db.avgexample.mapReduce(
map,
reduce,
{finalize:finalize, query: {name:"test1"}, out:"map_reduce_avg_example"}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment