Nested groups with aggregation framework
The process is to prepare from end level of array:
- subSubCategory (group by below 3 level of fields)
- subCategory (group by below 2 level of fields and push above prepared level 1)
- mainCategory (group by below 1 level of field and push above prepared level 2)
- group (project and show prepared level 3)
Lets look step by step,
- your
$match
condition
db.collection.aggregate([ { $match: { group: "Teknik" } },
$group
by with only 3 main fields, don't addsubSubCategory
- this group prepare
subSubCategory
array
{ $group: { _id: { group: "$group", mainCategory: "$mainCategory", subCategory: "$subCategory" }, subSubCategory: { $push: { name: "$subSubCategory" } } } },
- in above
$group
there will be chance of duplicatesubSubCategory
so this will remove duplicate, if you don't want to remove then you can skip this part
{ $addFields: { subSubCategory: { $setUnion: ["$subSubCategory", [] ] } } },
- now
$group
by only 2 main fields - this will prepares
subCategory
array, pushname
andsubSubCategory
array that we have prepared in above group
{ $group: { _id: { group: "$_id.group", mainCategory: "$_id.mainCategory" }, subCategory: { $push: { name: "$_id.subCategory", subSubCategory: "$subSubCategory" } } } },
$group
by maingroup
field- this will prepare
mainCategory
array, pushname
andsubCategory
array that we have prepared in above group
{ $group: { _id: "$_id.group", mainCategory: { $push: { name: "$_id.mainCategory", subCategory: "$subCategory" } } } },
$project
to remove_id
and showgroup
andmainCategory
fields
{ $project: { _id: 0, group: "$_id", mainCategory: 1 } }])
Playground: https://mongoplayground.net/p/Uw8HmhSKqzv