-
-
Save dimaip/17365161ad6e6615cd50bda4b75ad93c 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
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