Lesson 3: Using MongoDB Aggregation Stages with Java: $sort and $project / Learn
Using $sort and $project
Review the following code, which demonstrates how to build the $sort and $project stages of an aggregation pipeline in MongoDB with Java.
$sort and $project
In the following example, we use the Aggregates builder class to build the $sort and $project stages of an aggregation pipeline. This pipeline finds all checking accounts with a balance greater than 1500 and sorts the results in descending order. The query will return only four fields, including a newly computed Euro balance.
The match() method creates a $match pipeline stage that matches incoming documents against the specified query filter and filters out documents that don't match. Then, the sort() method creates a $sort pipeline stage to sort by the specified criteria. Finally, the project() method creates a $project pipeline stage that projects specified document fields. Field projection in aggregation follows the same rules as field projection in queries.
public static void main(String[] args) {
String connectionString = System.getProperty("mongodb.uri");
try (MongoClient mongoClient = MongoClients.create(connectionString)) {
MongoDatabase db = mongoClient.getDatabase("bank");
MongoCollection<Document> accounts = db.getCollection("accounts");
matchSortAndProjectStages(accounts);
}
}
private static void matchSortAndProjectStages(MongoCollection<Document> accounts){
Bson matchStage =
Aggregates.match(Filters.and(Filters.gt("balance", 1500), Filters.eq("account_type", "checking")));
Bson sortStage = Aggregates.sort(Sorts.orderBy(descending("balance")));
Bson projectStage = Aggregates.project(Projections.fields(Projections.include("account_id", "account_type", "balance"), Projections.computed("euro_balance", new Document("$divide", asList("$balance", 1.20F))), Projections.excludeId()));
System.out.println("Display aggregation results");
accounts.aggregate(asList(matchStage,sortStage, projectStage)).forEach(document -> System.out.print(document.toJson()));
}