In my collection I have an amount of documents that each contains 4 types of categories.
groupmainCategorysubCategorysubSubCategory
I'm looking for a way to $group this by group and inside group there should be an array of mainCategory, in mainCategory there should be an array of subCategory and in the subCategory there should be an array of the subSubCategory. The result should only contain the values/names of the categories.
Expected result:
const result = [
{
"group": "Teknik",
"mainCategory": [
{
"name": "Gaming",
"subCategory": [
{
"name": "Playstation",
"subSubCategory": [
{"name": "Games"},
{"name": "Accessories"},
{"name": "Console"}
]
},
{
"name": "Xbox",
"subSubCategory": [
{"name": "Games"},
{"name": "Accessories"},
{"name": "Console"}
]
}
]
}, {
"name": "Audio",
"subCategory": [
{
"name": "Headphones",
"subSubCategory": [
{"name": "Wireless"},
{"name": "Non Wireless"},
]
},
{
"name": "Speakers",
"subSubCategory": [
{"name": ""},
]
}
]
},
]
}
]
I think the problem is that I need to $push each and every category in the parent one and create new $groups? But when adding more $groups it's only the last one that is "saved". The other ones seems to not be "saved". Or is something else that im doing wrong?
Sample data and working code based on prev. test data.
https://mongoplayground.net/p/C0-L-rGPfwy
Product structure in the collection
productName :"Horizon Zero Dawn"
group:"Teknik"
mainCategory: "Gaming"
subCategory:"Playstation"
subSubCategory: "Games"
My aggregation
const categories = await Product.aggregate([
{$match: {group: 'Teknik'}},
{
$group: {
_id: {
group: '$group',
mainCategory: '$mainCategory',
subCategory: '$subCategory',
subSubCategory: '$subSubCategory',
}
},
},
{
$group: {
_id: "$_id.group",
mainCategory: {
$push:
{
name: "$_id.mainCategory",
subCategory: {
name: "$_id.subCategory",
subSubCategory: {
name: "$_id.subSubCategory"
}
}
}
},
}
},
]);
With this i get 1 object for each subSubcategory, but i would like them in the same object.
"_id": "Teknik",
"mainCategory": [
{
"name": "Gaming",
"subCategory": {
"name": "Xbox",
"subSubCategory": {
"name": "Games"
}
}
},
{
"name": "Spel & Gaming",
"subCategory": {
"name": "Xbox",
"subSubCategory": {
"name": "Accessories"
}
}
},
]