Video Transcript (English)
In this video, you’ll learn how to use the MongoDB PHP driver to create an aggregation pipeline.
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 you know the basics, let’s build an aggregation pipeline with the $match and $group stages.
For this example, we’ll work with bank account data. We want to: Find accounts with a balance of less than $1,000, group accounts by account type, either checking or savings, and calculate the average balance for each type.
We’ve established a connection to MongoDB and initialized the collection object. We’ll use the accounts collection in the bank database.
Here’s an example of a document from the collection to give you an idea of the structure.
Each document includes an account_id, account_holder, account_type, balance, and transfers_complete field. We’ll perform an aggregation on this dataset.
We open VSCode and load the sample app.
First, we create our client object and connect to our cluster. Then we create a reference to our collection, accounts.
Next, we write our aggregation pipeline as an array of stages. The first stage we create is a $match stage to query for documents that match the criteria, which is having a balance that’s less than 1000. We use the $lt operator.
Then we create our $group stage. For the $group stage, we must give the _id the key to group by. In this case, that's the account type. Then we define the fields that we expect in the groups, where we specify that we want the average balance for each of those account types. We use the $avg operator to find the average of the balances.
Great!
To run a pipeline, we use the aggregate() method. This method accepts an array. We will use the array stored in our pipeline variable. The aggregate operation returns a cursor object, and we use a cursor to iterate through the resulting documents.
Now that we’ve reviewed the pipeline, let’s run it. This is the output from the aggregation pipeline that uses both $match and $group.
We have two documents that contain: The _id that identifies the grouping value, checking or savings, and the average balance of each type of account.
Well done!
In this video, you learned about the $match and $group stages and how to implement them in an aggregation pipeline.