ошибка $ накопителя (агрегации) mongo db

#mongodb #mongodb-query

#mongodb #mongodb-запрос

Вопрос:

нужен hlep mongo с описанием, я скопировал эту часть :

 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"
      }
    }
  }
}
])
 

но я получаю сообщение об ошибке «errmsg»: «неизвестный оператор группы ‘$accumulator'»,
https://docs.mongodb.com/manual/reference/operator/aggregation/accumulator/#grp._S_accumulator

Комментарии:

1. Я думаю, что для простой суммы и среднего значения вам не нужна пользовательская функция аккумулятора. Возможно $reduce , может выполнить эту работу. Поскольку вы не предоставили ни образцов входных данных, ни желаемого результата, мы не можем помочь вам дальше.

Ответ №1:

Я столкнулся с той же проблемой. Проверьте свою версию MongoDB. $accumulator является новым в версии 4.4.

 > mongo --version
 

Постскриптум

Моя версия MongoDB была 4.2.5