How to Use Queries Using PHP
Introduction
If you’re a PHP developer who plans to work with MongoDB, you’ll probably need to query a MongoDB collection from a script at some point. Fortunately, MongoDB has an extensive query language, allowing you to create complex queries that return the exact data you need. In this article, we will demonstrate several examples of using queries in MongoDB using a PHP script.
Prerequisites
Before we check out the PHP code needed to create MongoDB queries, it’s important to confirm that certain prerequisites are met. For this tutorial, a few important system requirements include:
First, you’ll need to make sure that both MongoDB and the MongoDB PHP driver are properly configured before testing any queries.
To see if the MongoDB driver is already installed, use the following command in a terminal window:
1 | pecl search mongo |
- The output you see should look something like this:
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 |
- You will also need to have PHP installed and running. To find out which version of PHP is installed on your system, use the command shown below:
1 | php --version |
- The output from this command should look like the following:
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 |
Starting the MongoDB Database Daemon
Once you’ve taken care of all the system requirements, your next step will be to start the MongoDB database daemon. Open a terminal window by pressing Ctrl + Alt + T. Then, you can start up the MongoDB service and get a status check using the command shown below. Be sure to use the sudo
command to prevent any issues with permissions when starting the MongoDB service:
1 2 | sudo systemctl start mongod sudo systemctl status mongod |
After you start the MongoDB service, you will see output that looks 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) |
The Queries
Now that we’ve successfully started our MongoDB service, we can dive into the code and look at some MongoDB queries.
Note: Throughout this tutorial, the following table will be used as our sample data:
# | Position | Visible | Name |
---|---|---|---|
1 | 5 | true | AbiCorp |
2 | 3 | true | Onie |
3 | 2 | true | RommelDCode |
4 | 2 | true | AbiCorp |
5 | 1 | true | ThePresident |
1. Let’s begin with a simple example where we just find out how many documents are in a collection. The code shown below will count the number of documents found in a MongoDB collection:
1 2 3 4 5 6 | $con = new MongoDB\Client("mongodb://localhost:27017"); $db = $con->abi_db; $collection = $db->subjects->count(); echo $collection; |
2. In our next example, we’ll provide a more narrow query, looking for documents with a specific value in the position
field. The following code will display documents with a position
field having a value of 2:
1 2 3 4 5 6 7 8 9 10 11 12 | $filter = ['position' =>'2']; $options = []; $collection = $con->abi_db->subjects; $result = $collection->find($filter,$options); foreach ($result as $row){ echo "Topic Name : " . $row['topic_name']." "; } |
The results should look something like the following:
1 2 3 | Topic Name : RommelDCode Topic Name : AbiCorp |
The results can also be presented in a table format, as shown below:
# | Position | Visible | Name |
---|---|---|---|
1 | 2 | true | RommelDCode |
2 | 2 | true | AbiCorp |
3. What if we wanted to return documents where position
had a range of values instead of one specific value? In the following example, the code returns documents with a position
field having a value greater than 2 (expressed by using ‘$gt’ ):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | $filter = ['position'=>['$gt'=>'2']]; $options = []; $collection = $con->abi_db->subjects; $result = $collection->find($filter); foreach ($result as $row){ echo "Topic Name : " . $row['topic_name']." "; } |
The results should look something like this:
1 2 3 | Topic Name : AbiCorp Topic Name : Onie |
We could also present these results in a table format:
# | Position | Visible | Name |
---|---|---|---|
1 | 5 | true | AbiCorp |
2 | 3 | true | Onie |
4. Let’s try another example that involves a range of values. The code shown below returns documents with a position
field having a value that’s greater than or equal to 2 (expressed by using ‘$gte’ ).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | $filter = ['position'=>['$gte'=>'2']]; $options = []; $collection = $con->abi_db->subjects; $result = $collection->find($filter); foreach ($result as $row){ echo "Topic Name : " . $row['topic_name']." "; } |
The results should look something like this:
1 2 3 4 5 6 7 | Topic Name : AbiCorp Topic Name : Onie Topic Name : RommelDCode Topic Name : AbiCorp |
You can also present the results in a table format:
# | Position | Visible | Name |
---|---|---|---|
1 | 5 | true | AbiCorp |
2 | 3 | true | Onie |
3 | 2 | true | RommelDCode |
4 | 2 | true | AbiCorp |
5. In our final example, we’ll look at a query that performs some string matching.
The code shown below returns documents with a matching string ‘Rom’ found in the value of the topic_name
field:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | $filter = ['topic_name'=>new \MongoDB\BSON\Regex('Rom')]; $options = []; $collection = $con->abi_db->subjects; $result = $collection->find($filter); foreach ($result as $row){ echo "Topic Name : " . $row['topic_name']." "; } |
The results of the query should look like the following:
1 | Topic Name : RommelDCode |
The results can also be presented in a table format:
# | Position | Visible | Name |
---|---|---|---|
1 | 2 | true | RommelDCode |
Conclusion
When you use PHP to communicate with MongoDB, it’s important to know how to formulate a variety of queries. In this tutorial, we provided examples of several common queries that will get you off to a good start with PHP and MongoDB; however, it’s a good idea to experiment with different queries to become more familiar with MongoDB’s powerful, extensive query language. With the examples provided in this article, you’ll have no trouble using queries in MongoDB using PHP.
Pilot the ObjectRocket Platform Free!
Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.
Get Started