I have a product collection like this, simplified:
[
{
"_id": 1,
"ref": "product 1",
"variants": [
{
"ref": "variant 1.1",
"categories": ["category a"]
},
{
"ref": "variant 1.1",
"categories": ["category a","category b"]
}
]
},
{
"_id": 2,
"ref": "product 2",
"variants": [
{
"ref": "variant 2.1",
"categories": ["category c"]
},
{
"ref": "variant 2.1",
"categories": ["category a","category c"]
}
]
}
]
I want to query for categories (distinct), with their number of containing products (not variants).
For example some result like this:
[
"category a": 2,
"category b": 1,
"category c": 1
]
I tried some queries with aggregate and unwind, but I cannot figure it out. All help appreciated!
This is what I have so far:
[
{$match: ... }, // optional filtering
{$unwind: '$variants'},
{$unwind: '$variants.categories'},
]
But cannot figure out now, howto group by category, with a aggregate count of all products (not variants) inside that category.