.groupBy()
Given a Sequence or a List, buckets each item into groups, which then can run additional methods to aggregate by group.
This method is primarily used in Dashboards, which understand how to visualize aggregated results. It's foundational for common reporting aggregations to answer questions like "Break down our headcount by department".
The groupBy method itself returns a SequenceGroupedBy object which is not used directly. Instead, you can chain additional aggregation methods, like .sum() or .mean() onto it to return AggregatedResults that can be visualized in Dashboards.
Syntax
.groupBy{expression}
- Evalutes expression on each item in the Sequence or List, and buckets into groups based on the result of that expression
Examples
- [1, 2, 3, 4, 5].groupBy{it % 2 ? "Odd Numbers" : "Even Numbers"}.sum() will return an AggregatedResult of "Odd Numbers" = 9, "Even Numbers" = 4.
- db.job.find().groupBy{department}.count{gender:female} returns the number of Female-identified people in each department.
- db.job.find().groupBy{department:engineering,product ? 'R&D' : department:sales,marketing ? 'S&M' : 'G&A'}.sum{cost} returns the total cost of all jobs bucketed into three groups of `R&D', 'S&M', and 'G&A'.
-
