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