title: mongodb: sum of difference between two fields
body: <p>I am trying to build a query returning the difference between 2 fields. 
  Here are the documents of my collection:</p>
  
  <pre><code>[
   { _id: 1, type: 'in', amount: 10 },
   { _id: 2, type: 'in', amount: 5 },
   { _id: 3, type: 'out', amount: 7}
  ]
  </code></pre>
  
  <p>I am trying to get the <code>balance</code>: total of 'in' amount minus 'out' amount.
  The output should be something like:</p>
  
  <pre><code>{ ..., total: 8 } ( (10 + 5) - 7 )
  </code></pre>
  
  <p>This is what I have tried to do:</p>
  
  <pre><code>db.aggregate([
   {
     $group: {
       _id: '$type',
       total: { $sum: '$amount' } 
     }
   }
  ])
  </code></pre>
  
  <p>This just output the total per type:
  in --> 15,
  out --> 7</p>
  
  <p>How do I in a later stage find the difference of the above result?</p>
  
  <p>Thank you in advance</p>