I have seen lots posts to using aggregate
to sum
nested ARRAY
fields, I tried using it with my nested object which did not work.
When I query, the data structure is something like...
[
{
"key": "value",
"more_key": "more_value",
"meals": {
"A": {
"name": "salmon",
"amount": "8"
},
"B": {
"name": "vege",
"amount": "6"
},
}
},
{
"key": "value",
"more_key": "more_value",
"meals": {
"A": {
"name": "salmon",
"amount": "8"
},
"B": {
"name": "vege",
"amount": "6"
},
"C": {
"name": "other meal",
"amount": "6"
},
}
},
];
I am trying to sum the amount
I have tried something like this...
await Model.aggregate([
{ $match: { isDeleted: false } },
{ $unwind: '$meals' }, // tried with + without this
{ $group: { _id: null, sum: { $sumA: '$meals.A.amount', $sumB: '$meals.B.amount' } } }
]);
Can someone give me some advice and suggestion on how this can be done?
Thanks in advance.