Consider I have the following collection:
[
{
"total": 48.0,
"status": "CO"
},
{
"total": 11.0,
"status": "CA"
},
{
"total": 15916.0,
"status": "PE"
}
]
I need to realize the difference of PE status – (CO + CA).
The expected result is:
{
"_id" : null,
"total" : 15857.0
}
2
Answers
Use
$switch
to cater for different cases for your sum. Use$subtract
to flip the sign for the partial sum.Mongo Playground
Assuming these are the only
status
options, one way is to$group
using$cond
:See how it works on the playground example