I have a database with the following structure:
[
{
"provider": "provider 1",
"debts": [
{
"debt": 500,
"paid": true
},
{
"debt": 900,
"paid": false
},
{
"debt": 600,
"paid": false
}
]
},
{
"provider": "provider 2",
"debts": [
{
"debt": 500,
"paid": false
}
]
}
]
I want each object to store in the total field the sum of the debt field contained in the debts array (debts.debt) ONLY if thepaidproperty is false. (in my real code it works well up to here).
db.collection.aggregate(
[
{
$unwind: "$debts",
},
{
$group: {
_id: "$_id",
total: {
$sum: {
$cond: [{ $eq: ["$debts.paid", false] }, "debts.debt", 0],
},
},
},
}
]
how can I get the total of the sum of the total property contained in all my objects that met the above condition?
{
"debts_providers": [
{
"_id": "5f29af0a17196c1624f7dd88",
"total": 1500
},
{
"_id": "5f29af0a17196c1624f7dd89",
"total": 500
}
],
"sum_total_objects": 2000 /*900+600+500*/
}