Aggregation by field inside array

I have products collection with a “category” as array:

> { name: "ball", category: ["sport", "toys" ], quantity: 5 }
> { name: "gym bar", category: ["sport"], quantity: 3 }

How to aggregate by category in array ?
How to calc quantity of all products in each category ?

Expexted result - “sport”: 8, “toys”: 5

I tryed this …

        {$unwind: "$category"},
        {$group: {category: "$category", quantity: {$sum: "$quantity"}}}

Error: “The field ‘category’ must be an accumulator object”

Hello @Aleksander_Podmazko, Welcome to the MongoDB community forum,

The _id is the field to set group key for the document, it should be:

{$group: {_id: "$category", quantity: {$sum: "$quantity"}}}

See documentation for more details:


Thanks a lot, I unerstood it not right.