How to Perform Aggregation in MongoDB using PHP

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

Aggregation is how you can fine-tune your queries to get relevant returns, fast. In MongoDB, it’s a simplified way to slim down your data results so you see the meat minus the fluff. In essence, you save time when you run a query using aggregation. Find out more about it now. Learn how to apply the method with this step-by-step tutorial that explains how to perform aggregation in MongoDB using PHP.

Prerequisites:

  • MongoDB Download, install, and run it.

  • MongoDB PHP DriverDownload the correct driver for your MongoDB version.

  • Use the pecl command below to check that your MongoDB driver is installed:

  • Use this command to verify your PHP driver installation:

1
pecl search mongo
  • Here is what you should see:
1
2
3
Package Stable/(Latest) Local
mongo 1.6.16 (stable) MongoDB database driver
mongodb 1.6.0alpha1 (alpha) 1.5.3 MongoDB driver for PHP
  • Use this command to verify your MongoDB version installation:
1
php --version
    • Here is something like what you should see:
1
2
3
4
PHP 7.2.15-0ubuntu0.18.04.2 (cli) (built: Mar 22 2019 17:05:14) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
with Zend OPcache v7.2.15-0ubuntu0.18.04.2, Copyright (c) 1999-2018, by Zend Technologies

The MongoDB Database is Ready to Start

  • Use a sudo command and give yourself permissions to start the service for the MongoDB database. Do this by opening a terminal window and then pressing Ctrl + Alt + T.

  • Next, check the MongoDB service status with a sudo command.

1
2
sudo systemctl start mongod
sudo systemctl status mongod
  • You should see something like this.
1
2
3
4
5
6
7
8
9
10
‚óè mongod.service - MongoDB Database Server
Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset:
Active: active (running) since Mon 2019-04-22 19:27:02 PST; 8min ago
Docs: https://docs.mongodb.org/manual
Main PID: 6598 (mongod)
CGroup: /system.slice/mongod.service
└─6598 /usr/bin/mongod --config /etc/mongod.conf

Apr 22 19:27:02 teamsolo systemd[1]: Started MongoDB Database Server.
lines 1-9/9 (END)

About the Aggregate () Method

  • In MongoDB, aggregation is accomplished with pipeline operators. The filtering $match pipeline operator sorts through data from multiple documents, and based on the search criteria specified, returns the results.

>NOTE: The concept of how pipeline operators work is that after one set of criteria is matched, the next pipeline in the operation has another set of criteria that the documents must match. This continues until it narrows down to the last pipeline operator’s criteria of which the remaining documents are required to meet to be returned in the results.

  • This table example will set the stage for us to test the $match operator:
#PositionVisibleName
11falseThePresident
22trueRommelDCode
33trueAbiCorp
44trueOnie
55trueAbiCorp
66trueAbiClass
77falseAbiCreative

How to use the $match operator

  • The filtering $match operator is used as the first pipeline operator. After the criteria specified by $match is matched with documents, it’s finished. Now it’s ready to be passed over to the next pipeline operator’s criteria for matching whatever specified criteria that happens to be.

  • Let’s see it in action. Here’s the script for $match.

1
2
3
$allCorp = [
'$match'=>['topic_name'=>new \MongoDB\BSON\Regex('AbiC')]
];
  • Notice how the script shown above calls for the filtering of documents with the ‘ABic’ characters in the topic_name field.

How to use the $project operator

  • To further reduce pipeline funneling, use the $project operator.

  • See this example of where it shows only the topic_name field and the position in the collection.

1
$theVisible = ['$project' => ['topic_name' => 1, 'position' => 1]];

An Example of Pipeline Operators: The Entire Script

  • See the below script on how the passing of pipeline operators work in succession. After one set of criteria is matched, it is another operator’s turn to specify criteria.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
require_once('../../../private/initialize.php');


global $con;

$collection = $con->abi_db->subjects;

$allCorp = ['$match'=>['topic_name'=>new \MongoDB\BSON\Regex('AbiC')]];
$theVisible = ['$project' => ['topic_name' => 1, 'position' => 1]];
$result = $collection->aggregate(
[
$allCorp,$theVisible
]
);

// The values for ($result as $row) from the $result variable are here.{

echo "Topic Name : " . $row['topic_name']."
"
;
echo "Position : " . $row['position']."
"
;

// Since it is not in the $project parameter,
// an exception is thrown

echo "Visible : " . $row['visible']."
"
;
echo "

----------

"
;


}

Some error and error-free result examples from the above script

  • The visible field causes an error in this example.

Image Results with Error

  • Remove echo "Visible : " . $row['visible']." from the script and now it works fine.

Image Results without Error

Conclusion

This step-by-step tutorial showed you how to perform aggregation in MongoDB using PHP. You learned how to use the aggregate() method and how pipeline operators define specific criteria by which documents are filtered. We showed an example of how one pipeline operator used the filtering operator $match. When finished, it was passed on to the next operator’s criteria for further fine-tuning of results. “Efficient search” are two words that are synonymous with aggregation querying. Try it today and expand your coding repertoire, because aggregation in MongoDB is a technique that beginner developers can use to script like the pros.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.