Professional Documents
Culture Documents
/) Search docs
https://github.com/mongodb/mongo-java-
er/blob/master/docs/reference/content/driver/tutorials/aggregation.md)
Java Driver (/mongo-java-driver/4.1/driver/) Tutorials (/mongo-java-driver/4.1/driver/tutorials/) Aggregation
Aggregation Framework
The aggregation pipeline (http://docs.mongodb.org/manual/core/aggregation-pipeline ) is a framework
for data aggregation, modeled on the concept of data processing pipelines.
Prerequisites
The example below requires a restaurants collection in the test database. To create and populate
the collection, follow the directions in github (https://github.com/mongodb/docs-assets/tree/drivers).
Include the following import statements:
import com.mongodb.Block;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Aggregates;
import com.mongodb.client.model.Accumulators;
import com.mongodb.client.model.Projections;
import com.mongodb.client.model.Filters;
import org.bson.Document;
Include the following code which the examples in the tutorials will use to print the results of the
aggregation:
For example, include the following code to connect to a standalone MongoDB deployment running on
localhost on port 27017 and define database to refer to the test database and collection to refer to
the restaurants collection.
Perform Aggregation
To perform aggregation, pass a list of aggregation stages
(http://docs.mongodb.org/manual/meta/aggregation-quick-reference ) to the
MongoCollection.aggregate() (/mongo-java-driver/4.1/apidocs/mongodb-driver-
sync/com/mongodb/client/MongoCollection.html#aggregate(java.util.List) ) method. The Java driver
provides the Aggregates (/mongo-java-driver/4.1/apidocs/mongodb-driver-
core/com/mongodb/client/model/Aggregates.html ) helper class that contains builders for aggregation
stages.
collection.aggregate(
Arrays.asList(
Aggregates.match(Filters.eq("categories", "Bakery")),
Aggregates.group("$stars", Accumulators.sum("count", 1))
)
).forEach(printBlock);
collection.aggregate(
Arrays.asList(
Aggregates.project(
Projections.fields(
Projections.excludeId(),
Projections.include("name"),
Projections.computed(
"firstCategory",
new Document("$arrayElemAt", Arrays.asList("$categories", 0))
)
)
)
)
).forEach(printBlock);