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:

pecl search mongo
  • The output you see should look something like this:
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:
php --version
  • The output from this command should look like the following:
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:

sudo systemctl start mongod
sudo systemctl status mongod

After you start the MongoDB service, you will see output that looks something like this:

‚óè 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:

#PositionVisibleName
15trueAbiCorp
23trueOnie
32trueRommelDCode
42trueAbiCorp
51trueThePresident

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:

$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:

$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:

Topic Name : RommelDCode

Topic Name : AbiCorp

The results can also be presented in a table format, as shown below:

#PositionVisibleName
12trueRommelDCode
22trueAbiCorp

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’ ):

$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:

Topic Name : AbiCorp

Topic Name : Onie

We could also present these results in a table format:

#PositionVisibleName
15trueAbiCorp
23trueOnie

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’ ).

$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:

Topic Name : AbiCorp

Topic Name : Onie

Topic Name : RommelDCode

Topic Name : AbiCorp

You can also present the results in a table format:

#PositionVisibleName
15trueAbiCorp
23trueOnie
32trueRommelDCode
42trueAbiCorp

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:

$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:

Topic Name : RommelDCode

The results can also be presented in a table format:

#PositionVisibleName
12trueRommelDCode

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.

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.