0

I am trying to build a query returning the difference between 2 fields. Here are the documents of my collection:

[
 { _id: 1, type: 'in', amount: 10 },
 { _id: 2, type: 'in', amount: 5 },
 { _id: 3, type: 'out', amount: 7}
]

I am trying to get the balance: total of 'in' amount minus 'out' amount. The output should be something like:

{ ..., total: 8 } ( (10 + 5) - 7 )

This is what I have tried to do:

db.aggregate([
 {
   $group: {
     _id: '$type',
     total: { $sum: '$amount' } 
   }
 }
])

This just output the total per type: in --> 15, out --> 7

How do I in a later stage find the difference of the above result?

Thank you in advance

TheSoul
  • 4,906
  • 13
  • 44
  • 74

1 Answers1

0

$group with an _id of null and use $cond to make the value either positive or negative. Specifically, if type is not in, then you can use $multiply to multiply the $total by -1. Something like the following should work:

db.aggregate([
  {
    $group: {
      _id: '$type',
      total: { $sum: '$amount' } 
    }
  },
  {
    $group: {
      _id: null,
      total: { $sum: { $cond: {
        if: { $eq: [ '$_id', 'in']},
        then: '$total',
        else: { $multipy: [ '$total', -1 ]}
      }}}
    }
  }
])
B. Fleming
  • 7,170
  • 1
  • 18
  • 36