Given the following data after unwinding in an aggregate:
let workOrders = [
{customer: 'A', job: 'Apple', chemical: {name: 'Chem A', quantity: 500}},
{customer: 'A', job: 'Banana', chemical: {name: 'Chem B', quantity: 400}},
{customer: 'A', job: 'Banana', chemical: {name: 'Chem C', quantity: 300}},
{customer: 'B', job: 'Cherry', chemical: {name: 'Chem A', quantity: 200}}
]
Output needed:
[
{
customer: 'A',
jobs: [
{
job: 'Apple',
chemicals: [
{name: 'Chem A', quantity: 500}
]
},
{
job: 'Banana',
chemicals: [
{name: 'Chem B', quantity: 400},
{name: 'Chem C', quantity: 300}
]
}
]
},
{
customer: 'B',
jobs: [
{
job: 'Cherry',
chemicals: [
{name: 'Chem A', quantity: 200}
]
}
]
}
]
I understand how to use group and group it by customer first, but then I don't understand how to make the nested chemicals array without messing up the initial customer group.
I tried something like this but it doesn't like the inner $push.
{
"$group": {
"_id": "$customer",
"groups": {
$push: {
"group_data": "$customer",
"group_count": {$sum: "$customer"},
"group_child": {
$push: {
"group_data": "$job",
"group_count": {$sum: "$job"},
"group_children": {
$push: {
"group_data": "$chemical.name",
"group_count": {$sum: "$chemical.name"}
}
}
}
}
}
}
}
Also would like to add the total of quantity per Customer and per Job