Last active
September 11, 2021 20:37
-
-
Save ufeanei/53255767d3664a0904c898d08518426e to your computer and use it in GitHub Desktop.
Mongo aggregation grouping by categories then grouping by subcategories
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
consider the collection shown below | |
[ | |
{ | |
_id: 1, | |
category: "A", | |
subCategory: "a1", | |
}, | |
{ | |
_id: 2, | |
category: "A", | |
subCategory: "a1", | |
}, | |
{ | |
_id: 3, | |
category: "A", | |
subCategory: "a2", | |
}, | |
{ | |
_id: 4, | |
category: "C", | |
subCategory: "c2", | |
}, | |
{ | |
_id: 5, | |
category: "B", | |
subCategory: "b1", | |
}, | |
{ | |
_id: 6, | |
category: "B", | |
subCategory: "b1", | |
} | |
] | |
the following aggregation will group the documents per category and sub category. this is very useful for e-commerce faceted search | |
db.collection.aggregate([ | |
{ | |
$group: { | |
_id: { | |
category: "$category", | |
subCategory: "$subCategory" | |
}, | |
count: { | |
$sum: 1 | |
} | |
} | |
}, | |
{ | |
$group: { | |
_id: "$_id.category", | |
v: { | |
$push: { | |
subCategory: "$_id.subCategory", | |
sum: "$count" | |
} | |
}, | |
s: { | |
$sum: "$count" | |
} | |
} | |
}, | |
]) | |
the result obtained form the above aggregation pipeline is as follows | |
[ | |
{ | |
"_id": "B", | |
"count": 2, | |
"v": [ | |
{ | |
"subCategory": "b1", | |
"sum": 2 | |
} | |
] | |
}, | |
{ | |
"_id": "A", | |
"count": 3, | |
"v": [ | |
{ | |
"subCategory": "a1", | |
"sum": 2 | |
}, | |
{ | |
"subCategory": "a2", | |
"sum": 1 | |
} | |
] | |
}, | |
{ | |
"_id": "C", | |
"count": 1, | |
"v": [ | |
{ | |
"subCategory": "c2", | |
"sum": 1 | |
} | |
] | |
} | |
] | |
see the mongo playground at https://mongoplayground.net/p/WfEC2xAmriJ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment