I'm trying to create some nested fields in $group stage of aggregation. I get the error that "stats" must be an accumulator. Is there any way to insert these nested fields?
model.aggregate( [ {
$group: {
_id: '$groupName,
nestedFields: {
field1: {
$sum: { $multiply: [ '$num1', '$num2'] }
},
field2: { $sum: '$num3' }
}
}
} ] )
Any help is greatly appreciated.
edit: some sample data INPUT:
{
"groupName": 1
"num1": 2,
"num2": 4,
"num3": 8,
}
{
"groupName": 1
"num1": 2,
"num2": 7,
"num3": 1,
}
{
"groupName": 2
"num1": 1,
"num2": 3,
"num3": 5,
}
{
"groupName": 2
"num1": 6,
"num2": 1,
"num3": 2,
}
should OUTPUT through the aggregation:
{
"_id": 1,
"nestedFields": {
"field1": 22, // 2*4 + 2*7
"field2": 9, // 8 + 1
}
},
{
"_id": 2,
"nestedFields": {
"field1": 9,
"field2": 7,
}
}
$addFieldsor$project