Video Transcript (English)
Hello! In this video, you’ll learn how to build an aggregation pipeline by using the Aggregates builder class. Specifically, you’ll learn how to use the $match and $group stages in an aggregation pipeline.
Let’s start with an overview of the $match and $group stages.
The $match stage filters documents to pass only the documents that match the specified conditions to the next stage of the pipeline.
The $group stage separates documents into groups according to a group key. The output of this stage is one document for each unique group key.
Now that we know the basics, let’s build an aggregation pipeline with the $match and $group stages that finds: An account belonging to Puja Barbier, given an account number, and The average balance and the total balance for Puja’s savings and/or checking accounts.
For this example, we’ll assume that we have already established a connection to MongoDB and initialized the collection object.
We’ll use the banking accounts dataset. Here’s an example of a document from the collection that we’ll work with. To perform an aggregation, pass a list of one or more aggregation stages to the MongoCollection.aggregate() method.
In the $match stage, we’ll achieve our first requirement by finding Puja Barbier’s account.
$match is the first stage in the pipeline. It matches incoming documents with the account_id query filter, filtering out documents that do not match.
In this example, we’ll use the Aggregates builder class to define the match stage. We’ll use the Filters builder class to specify which account we’re searching for.
Now we’ll pass the MongoCollection’s aggregate method an array of aggregation stages that we want to execute. Here, we pass in the filter we previously defined for the $match stage.
The aggregate method returns an AggregateIterable<Document>.
Then, we print out a statement that tells us what the forEach loop prints out next.
After executing the pipeline, we print the results of the aggregation by iterating the results.
Next, we need to find the average balance and total balance for Puja’s savings and checking accounts. We’ll use the $group stage to summarize this data in our collection.
Remember , the $group stage separates documents into groups according to a group key. In this example, the group key is the account_type. The output is one document for each unique group key.
The $group stage uses operators known as accumulators. These include the $avg and $sum accumulators that help to summarize the data. Here, the balance of Puja’s account types are added to find the total_balance and then averaged to find the average_balance.
Then, we pass the groupStage into the aggregate() method. After we execute the aggregation pipeline, we can iterate the results that are returned and print the documents.
Well done! In this video, you learned about the $match and $group stages and how to implement them by using the Aggregates builder class.