Skip to content

Instantly share code, notes, and snippets.

@Pyrolistical
Forked from RedBeard0531/functions.js
Last active December 28, 2017 04:10
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save Pyrolistical/8139958 to your computer and use it in GitHub Desktop.
Save Pyrolistical/8139958 to your computer and use it in GitHub Desktop.
Mongo map reduce functions to calculate sum, min, max, count, average, population variance, sample variance, population standard deviation, sample standard deviation Public Domain License
function map() {
emit(1, {
sum: this.value, // the field you want stats for
min: this.value,
max: this.value,
count: 1,
diff: 0
});
}
function reduce(key, values) {
return values.reduce(function reduce(previous, current, index, array) {
var delta = previous.sum/previous.count - current.sum/current.count;
var weight = (previous.count * current.count)/(previous.count + current.count);
return {
sum: previous.sum + current.sum,
min: Math.min(previous.min, current.min),
max: Math.max(previous.max, current.max),
count: previous.count + current.count,
diff: previous.diff + current.diff + delta*delta*weight
};
})
}
function finalize(key, value) {
value.average = value.sum / value.count;
value.population_variance = value.diff / value.count;
value.population_standard_deviation = Math.sqrt(value.population_variance);
value.sample_variance = value.diff / (value.count - 1);
value.sample_standard_deviation = Math.sqrt(value.sample_variance);
delete value.diff;
return value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment