$accumulator (aggregation) error mongo db

need hlep mongo with the doumrntation,
i copied this part :

db.books.aggregate([
{
  $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"
      }
    }
  }
}
])

but im getting an error "errmsg" : "unknown group operator ‘$accumulator’",
https://docs.mongodb.com/manual/reference/operator/aggregation/accumulator/#grp._S_accumulator

16 thoughts on “$accumulator (aggregation) error mongo db”

Leave a Comment