title: MongoDB Mongoose aggregation / math operations
body: <p>I am having a problem with understanding how the <code>$aggregation</code> method works in Mongoose. To be honest, I couldn't found any code examples in mongoose docs (I haven't found even [search] option on their site [google site:mongoosejs.com helps me])</p>
  <p>So, I hope someone will help me to explain this and answer my question.</p>
  <p>For example, I have various documents in my collection, with fields:</p>
  <pre><code>    { &quot;_id&quot;: 1, &quot;item&quot;:47139, &quot;total_price&quot;: 560000, &quot;quantity&quot;: 56, &quot;lastModified&quot; : 1491748073000 }
      { &quot;_id&quot;: 3, &quot;item&quot;:47140, &quot;total_price&quot;: 1750000, &quot;quantity&quot;: 150, &quot;lastModified&quot; : 1491748073000 }
  </code></pre>
  <p>and I would like to <code>$sum</code> all the &quot;quantity&quot; for documents with <code>id: 47139</code> and <code>timestamp: 1491748073000</code>. As for now this code works fine and provides me the necessary data:</p>
  <pre><code>    var server = mongoose.model('Name_of_my_Schema', Schema);
  
      server.find({ lastModified : 1491748073000, item : 47139 }, null, {sort: 'buyout'},function (err, res) {
          total = 0;
          for (i = 0; i &lt; res.length; i++) {  //sorry, map.reduce, but not this time
              total += res[i].quantity; 
          }
          console.log(total); //in this case total = 256
      });
  </code></pre>
  <p>but is it possible to do this operation via mongoose? According to mongo docs I should use this code for matching the necessary array of docs, like these:</p>
  <pre><code>  server.aggregate().match({
     lastModified : 1491748073000,
      item : 47139
    }).exec(function (err, result){
      console.log(result);
       console.log(err);
    });
  </code></pre>
  <p>and then use the <code>$group</code> to group the necessary data and <code>{ $sum: &quot;quantity&quot; }</code>, but what I should do next? Why should I use a $group, if I just want to receive a sum of all quantity?</p>
  <p>Could someone give me a clue what am I missing?</p>