title: Sum array elements in Mongodb aggregation
body: <p>I have the following collection with <code>c</code> array inside each document</p>
  
  <pre><code>{
    {
      id: 1,
      k: 2.2,
      type: "dog",
      c: [ {parentId:1, p:2.2}, {parentId:1, p:1.4} ]
    },
  
    {
      id: 2,
      k: 4.3,
      type:"cat",
      c: [ {parentId:2, p:5.2}, {parentId:2, p:4.5} ]
    }
  }
  </code></pre>
  
  <p><code>parentId</code> inside each subdocument in <code>c</code> is id of containing document.</p>
  
  <p>I want to group all docs by <code>type</code> and in each group know sum of <code>k</code> and sum of all <code>p</code> in all arrays of the group.</p>
  
  <p>Currently I do summation of <code>k</code> in the group stage but summation of <code>p</code> in the result array in the application. I want to do summation of <code>p</code> in DB!</p>
  
  <p>This is what I do currently:</p>
  
  <pre><code>db.myCol.aggregate([
  
  { 
    $group: {
      _id: { type: '$type'},
      k: {$sum: '$k'}, // sum k values, very easy!
      // p: {$sum: '$c.0.p'} &lt;==== Does not work, too
      c: {$addToSet: '$c'} // add to each group all c arrays of group's members
    }   
  }
  ], function(err, res) {
     // go over c-arrays and sum p values
     var accP = 0; // accumulator for p values
     for ( var i=0; i&lt;res.length; i++ ) {
       var c = res[i].c;
       for (var j=0;j&lt;c.length; j++) {
         var c2 = c[j];
         for ( var k=0; k&lt;c2.length; k++) { // finally got to objects c array
            accP += c2[k].p;
         }
       }
       res[i].c = accP; // replace array with accumulated p value
     }
  });
  </code></pre>