title: How to $add together a subset of elements of an array in mongodb aggregation?
body: <p>Here is the problem I want to resolve:</p>
  
  <ul>
  <li>each document contains an array of 30 integers</li>
  <li>the documents are grouped under a certain condition (not relevant here)</li>
  <li>while grouping them, I want to:
  <ul>
  <li>add together the 29 last elements of the array (skipping the first one) of each document</li>
  <li>sum the previous result among the same group, and return it</li>
  </ul></li>
  </ul>
  
  <p>Data structure is very difficult to change and I cannot afford a migration + I still need the 30 values for another purpose. Here is what I tried, unsuccessfully:</p>
  
  <pre><code>db.collection.aggregate([
      {$match: {... some matching query ...}},
      {$project: {total_29_last_values: {$add: ["$my_array.1", "$my_array.2", ..., "$my_array.29"]}}},
      {$group: {
          ... some grouping here ...
          my_result: {$sum: "$total_29_last_values"}
      }}
  ])
  </code></pre>
  
  <p>Theoretically (IMHO) this should work, given the definition of $add in mongodb documentation, but for some reason it fails:</p>
  
  <pre><code>exception: $add only supports numeric or date types, not Array
  </code></pre>
  
  <p>Maybe there is not support for adding together elements of an array, but this seems strange...</p>
  
  <p>Thanks for your help !</p>