MongoDB can perform aggregation operations, such as grouping by a specified key and evaluating a total or a count for each distinct group. Use the aggregate method to perform a stage-based aggregation. The aggregate method accepts as its argument an array of stages, where each stage, processed sequentially, describes a data processing step.
The examples in this section use the restaurants collection in the test database. For instructions on populating the collection with the sample dataset, see Import Example Dataset. Follow the Connect to MongoDB step to connect to a running MongoDB instance and declare and define the variable db to access the test database. To begin, including the following import statements.
Use the $group stage to group by a specified key. In the $group stage, specify the group by key in the _id field. $group accesses fields by the field path, which is the field name prefixed by a dollar sign $. The $group stage can useaccumulators to perform calculations for each group. The following example groups the documents in the restaurants collection by the borough field and uses the $sum accumulator to count the documents for each group.
The _id field contains the distinct borough value, i.e., the group by key value.
Filter and Group Documents
Use the $match stage to filter documents. $match uses the MongoDB query syntax. The following pipeline uses $match to query the restaurants collection for documents with borough equal to "Queens" and cuisine equal to Brazilian. Then the $group stage groups the matching documents by the address.zipcode field and uses the $sum accumulator to calculate the count. $group accesses fields by the field path, which is the field name prefixed by a dollar sign $.
The _id field contains the distinct zipcode value, i.e., the group by key value.
In the Java Driver documentation, see aggregate, AggregateIterable, Block; In the MongoDB Manual, see also Aggregation Quick Reference, the SQL to Aggregation Mapping Chart, and Aggregation Introduction.
* Getting Started - Remove Data with Java Driver
* Getting Started - Indexes with Java Driver