I have a mongoDB collection and I want to do an aggregation query.
I am grouping by alert_type field, but I also want the list of those alert_type as a separate field in the output.
Collection looks like this :
db.test.insertMany([ { "output_data": { "alert_type": "UAlert", "overallImpact": { "margin": 0.1, "workingCapital": 3.33 } } }, { "output_data": { "alert_type": "CAlert", "overallImpact": { "margin": 0.1, "workingCapital": 3.33 } } }, { "output_data": { "alert_type": "UAlert", "overallImpact": { "margin": 0.1, "workingCapital": 3.33 } } } ]) Query that I have tried :
db.test.aggregate([ {$group: { "_id": "$output_data.alert_type", "alert_type": { "$first": "$output_data.alert_type" }, "margin": { "$sum": "$output_data.overallImpact.margin" }, "workingCapital": { "$sum": "$output_data.overallImpact.workingCapital" }, "alert_types": { "$addToSet": "$output_data.alert_type" } } }, {$project: {'_id': 0 } } ]) Current output :
{ "alert_type": "UAlert", "margin": 0.2, "workingCapital": 6.66, "alert_types": [ "UAlert" ] } { "alert_type": "CAlert", "margin": 0.1, "workingCapital": 3.33, "alert_types": [ "CAlert" ] } Required Output :
{ "data": [ { "alert_type": "UAlert", "margin": 0.2, "workingCapital": 6.66, }, { "alert_type": "CAlert", "margin": 0.1, "workingCapital": 3.33, } ], "alert_types": [ "UAlert", "CAlert" ] } Can anyone help me out with this?