Lesson 2: Using MongoDB Aggregation Stages with Java: $match and $group / Learn

Using $match and $group

Review the following code, which demonstrates how to build the $match and $group stages of an aggregation pipeline in MongoDB with Java.

$match and $group

In both of the following examples, we use the Aggregates builder class to build the $match and $group stages of an aggregation pipeline.

First, we use $match to find an account that belongs to a customer. We start by creating a new method called matchStage that we call in the main method. In matchStage, we use the Filters builder class to specify which account we're searching for. 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.

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");
        matchStage(accounts);
    }
}

private static void matchStage(MongoCollection<Document> accounts){
    Bson matchStage = Aggregates.match(Filters.eq("account_id", "MDB310054629"));
    System.out.println("Display aggregation results");
    accounts.aggregate(Arrays.asList(matchStage)).forEach(document->System.out.print(document.toJson()));
}


In the next example, we use $match and $group to find the average and total balances of the customer's accounts. We start by creating a new method called matchAndGroupStages that we call in the main method. 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. The group() method then creates a $group pipeline stage to group documents by a specified expression and output a document for each distinct grouping.

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");
        matchAndGroupStages(accounts);
    }
}

private static void matchAndGroupStages(MongoCollection<Document> accounts){
    Bson matchStage = Aggregates.match(Filters.eq("account_id", "MDB310054629"));
    Bson groupStage = Aggregates.group("$account_type", sum("total_balance", "$balance"), avg("average_balance", "$balance"));
    System.out.println("Display aggregation results");
    accounts.aggregate(Arrays.asList(matchStage, groupStage)).forEach(document->System.out.print(document.toJson()));
}