Let's say we have a collection with documents as below
{_id:1, name:'a', category:'c1', count:1}
{_id:2, name:'b', category:'c1', count:3}
{_id:3, name:'c', category:'c1', count:5}
{_id:4, name:'d', category:'c2', count:2}
{_id:5, name:'e', category:'c2', count:3}
{_id:6, name:'f', category:'c2', count:6}
{_id:7, name:'g', category:'c2', count:7}
I'm trying to construct some sort of "aggregation"
pipeline to
- Group documents by category
- For each category, return top 2 documents by count in descending order
So in this case, the expected result should be something like
[
{_id:'c1: docs:[
{_id:3, name:'c', category:'c1', count:5},
{_id:2, name:'b', category:'c1', count:3}
]},
{_id:'c2: docs:[
{_id:7, name:'g', category:'c2', count:7},
{_id:6, name:'f', category:'c2', count:6}
]},
]
Currently, I take multiple steps to produce the result
- Identify category list
- Repeat find {category:x}, {sort:[['count', 'desc']], limit:2} command
- Merge results into one common array
Is there anyway to achieve this in "aggregation"
manner?