I have the following docs in my collection –
{
name: 'test1',
score: 80
},
{
name: 'test2',
score: 50
},
{
name: 'test3',
score: 100
},
{
name: 'test4',
score: 70
}
I would like to aggregate and group those docs, based on scores ranges – 0-60, 61-90, 91-100
so the results will look like –
{
score: '0-60',
tests: ['test2']
},
{
score: '61-90',
tests: ['test1', 'test4']
},
{
score: '91-100',
tests: ['test3']
}
Can I somehow group values by ranges in MongoDB?
2
Answers
playground
You may check also the $bucketAuto aggregation operator which allow you to auto group by range based on number of ranges:
Explained: You provide the field in groupBy by which you need to group and you provide the number of ranges.
Playground