Let's say I have a collection with the following (dummy) data:
| Country | State | Population Density (people per km^2) | Cases (in millions) |
|---|---|---|---|
| USA | New York | 161 | 1.03 |
| USA | California | 95 | 4.47 |
| Germany | Berlin | 4,227 | 0.19 |
| India | Kerala | 859 | 4.09 |
| India | Karnataka | 319 | 2.95 |
| India | Maharashtra | 370 | 6.47 |
What is an optimized mongodb query to get results grouped by country and sorted by the count of states, also each group should contain states sorted by 'Cases'?
The results should look like this in JSON
{
'results': [
{
'country' : 'India',
'num_states': 3,
'states': [
{
'State': 'Maharashtra',
'Cases': 6.47,
'PPD' : 370,
},
{
'State': 'Kerala',
'Cases': 4.09,
'PPD' : 859,
},
{
'State': 'Karnataka',
'Cases': 2.95,
'PPD' : 319,
}
]
},
{
'country' : 'USA',
'num_states': 2,
'states': [
{
'State': 'California',
'Cases': 4.47,
'PPD' : 95,
},
{
'State': 'New York',
'Cases': 1.03,
'PPD' : 161,
}
]
},
{
'country' : 'Germany',
'num_states': 1,
'states': [
{
'State': 'Berlin',
'Cases': 0.19,
'PPD' : 4227,
}
]
},
]
}
Note: My actual data is different, but the use case is the same.