Skip to content

Instantly share code, notes, and snippets.

@jorisvddonk
Created April 28, 2015 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jorisvddonk/e7e2d0bab78ec1e22634 to your computer and use it in GitHub Desktop.
Save jorisvddonk/e7e2d0bab78ec1e22634 to your computer and use it in GitHub Desktop.
Example custom operators for Mingo
/*
$pluck is a pipeline operator which returns the result of resolving `expr` on each item in the collection.
This allows you to 'boil down' a collection to just the values you're interested in.
Example:
Mingo.aggregate(grades_complex, [{$unwind: "$scores"}, {$pluck: "scores.score"}]);
returns an array of all scores in the 'grades_complex' dataset: [57.92947112575566, 21.24542588206755, 68.1956781058743, 67.95019716560351, 18.81037253352722, 39.17749400402234, ...]
*/
Mingo.addOperators(Mingo.OP_PIPELINE, function(m) {
return {
'$pluck': function(collection, expr) {
return collection.map(function(item) {
return m.resolve(item, expr);
});
}
};
});
/*
$stddev is an operator which returns the standard deviation of all the values in a group.
Example:
Mingo.aggregate(grades_complex, [{$unwind: "$scores"}, {$group: {$stddev: "$scores.score"}}]);
returns: [{$stddev: 28.57362029450366}]
*/
Mingo.addOperators(Mingo.OP_GROUP, function(m) {
return {
'$stddev': function(collection, expr) {
var avg = this.$avg(collection, expr);
var diffs = _.map(collection, function(item) {var v = m.computeValue(item, expr) - avg; return v*v});
var variance = _.reduce(diffs, function (memo, val) {return memo + val}, 0) / diffs.length;
return Math.sqrt(variance);
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment