-
Type:
Improvement
-
Resolution: Done
-
Priority:
Minor - P4
-
None
-
Affects Version/s: 2.6.5, 2.8.0-rc2
-
Component/s: Aggregation Framework
-
None
-
None
-
None
-
None
-
None
-
None
-
None
-
None
Suppose I have the following documents:
db.country.insert(
{
"region" : "EMEA",
"country" : "France",
"count": 10
}
);
db.country.insert(
{
"region" : "EMEA",
"country" : "Germany",
"count": 30
}
);
db.country.insert(
{
"region" : "AMERICAS",
"country" : "USA",
"count": 15
}
);
db.country.insert(
{
"region" : "AMERICAS",
"country" : "Canada",
"count": 20
}
);
I want to get the following stats out of this database:
- Number of document per regions, per country
- sum (or avg...) of the "count" for each region and country
AFAIK in MongoDB I need to use 2 aggregate calls:
// for Region
db.country.aggregate([
{ $group : { _id : "$region", doc_count : {$sum : 1} , total : { $sum : "$count" } } }
]);
result:
{ "_id" : "AMERICAS", "doc_count" : 2, "total" : 35 }
{ "_id" : "EMEA", "doc_count" : 2, "total" : 40 }
// For country inside a region
db.country.aggregate([
{ $group : { _id : { region : "$region" , country : "$country" }, doc_count : {$sum : 1} , total : { $sum : "$count" } } }
]);
result:
{ "_id" : { "region" : "AMERICAS", "country" : "USA" }, "doc_count" : 1, "total" : 15 }
{ "_id" : { "region" : "AMERICAS", "country" : "Canada" }, "doc_count" : 1, "total" : 20 }
{ "_id" : { "region" : "EMEA", "country" : "Germany" }, "doc_count" : 1, "total" : 30 }
{ "_id" : { "region" : "EMEA", "country" : "France" }, "doc_count" : 1, "total" : 10 }
>> May be it is possible to do it with some "hacks" in the aggregation pipeline, but I have not found it yet.
It would be useful to group by firs level and have an option to create sub document for each sub element. To be honest I do not have think through the full process (developer experience, result, limitations)
This feature will make the life easier to developers to create dashboard for example