Skip to content

Instantly share code, notes, and snippets.

@dimaip
Created August 27, 2020 06:28
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 dimaip/17365161ad6e6615cd50bda4b75ad93c to your computer and use it in GitHub Desktop.
Save dimaip/17365161ad6e6615cd50bda4b75ad93c to your computer and use it in GitHub Desktop.
Model.aggregate().facet({
someKey: [
{
$group :
{
_id : "$author",
avgCopies:
{
$accumulator:
{
init: function() { // Set the initial state
return { count: 0, sum: 0 }
},
accumulate: function(state, numCopies) { // Define how to update the state
return {
count: state.count + 1,
sum: state.sum + numCopies
}
},
accumulateArgs: ["$copies"], // Argument required by the accumulate function
merge: function(state1, state2) { // When the operator performs a merge,
return { // add the fields from the two states
count: state1.count + state2.count,
sum: state1.sum + state2.sum
}
},
finalize: function(state) { // After collecting the results from all documents,
return (state.sum / state.count) // calculate the average
},
lang: "js"
}
}
}
}
],
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment