Lesson 2: Using MongoDB Aggregation Stages with PHP: Match and Group / Learn
Code Summary: Using MongoDB Aggregation Stages with PHP: Match and Group
Review the following code, which demonstrates how to use the $match and $group stages in a MongoDB aggregation pipeline by using the MongoDB PHP library.
Using $match
Use the $match stage to select documents that match the specified query condition(s) and pass the matching documents to the next stage. $match takes a document that specifies the query.
$match should be placed early in a pipeline to reduce the number of documents that will be processed later in the pipeline.
Here's an example of the $match stage:
// Select accounts with balances of less than $1000
{ "$match":
{ "balance":
{ "$lt": 1000 }
}
}
Using $group
Use the $group stage to separate documents into groups. The $group stage must have an _id field that specifies the group key. The group key is preceded by a $ and enclosed in quotation marks.
A $group stage can include additional fields that are computed by using accumulator operators, such as $avg.
Here's an example of the $group stage:
// Separate documents by account type and calculate the average balance for
// each account type
{ "$group":
{ "_id": "$account_type", "avg_balance": { "$avg": "$balance" } }
}
Aggregation Example That Uses $match and $group
The following is an example of an aggregation pipeline that uses $match and $group in PHP.
<?php
require_once __DIR__ . '/vendor/autoload.php';
$client = new MongoDB\Client('<Atlas-connection-string>');
$accountsCollection = $client->bank->accounts;
$pipeline = [
['$match' => ['balance' => ['$lt' => 1000]]],
['$group' => [
'_id' => '$account_type',
'avg_balance' => ['$avg' => '$balance'],
]],
];
$cursor = $accountsCollection->aggregate($pipeline);
foreach ($cursor as $result){
var_dump($result);
}