How to Loop through MongoDB Query Results using PHP

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

Introduction

We know that looping saves time coding because repeating the same steps manually is cumbersome and unnecessary. Loops allow you to drill down the details. For example, your query can contain a loop where the script proceeds to find documents that meet the first condition of values, then the next condition of values, and finally return the results after another set of values has been met. The best way to grow with loops is to write out some code and test a few scripts. Reading this tutorial about looping through MongoDB query results using PHP is a great place to start.

Prerequisites

  • Install and run the current, stable version of MongoDB.
  • Install a compatible MongoDB PHP Driver for MongoDB.

  • Below is the pecl command, use it to check that you’ve installed the MongoDB driver:

1
pecl search mongo
  • Here’s a result indicating a successful installation. You should see something similar to it:
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
  • Make sure the correct PHP version is installed with this command:
1
php --version
  • You should see a similar result like this successful output:
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

How to Quickly Start the MongoDB Database Service

  • Press Ctrl + Alt + T to open your terminal.

  • You’ll need permissions to start MongoDB. You’ll also want to check the status of the service once it starts. To accomplish both tasks, use the following commands:

1
2
sudo systemctl start mongod
sudo systemctl status mongod
  • Your screen should look like this or close to it:
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)

An example of the While loop

  • Use a While loop when you want to see results if documents meet a true condition. If no documents meet the condition stated in the While loop, it won’t run.

  • Here’s an example of the While loop function in MongoDB.

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
$db = new MongoDB\Driver\Manager("mongodb://localhost:27017");

$db = $con->abi_db;
$collection = $db->subjects;
$cursor = $collection->find();
$itr = new IteratorIterator($cursor); // (1)
$itr -> rewind(); // (2)

echo "

# "
. "For While Loop Sample" . "

"
;

while ($cursor = $it->current()){ // (3)

echo $cursor['topic_name']."
"
;
echo $cursor['visible']."
"
;
echo $cursor['position']."
"
;
echo "

----------

"
;

$itr->next(); // (4)
}

(1) The IteratorIterator class is a wrapper that converts transverable things into interators.

(2) rewind() returns to the beginning element.

(3) current() will obtain the value that is current.

(4) next() proceeds to the following value.

  • After you created the script, save the file as loop.php.

  • In your web browser, go to the file.

  • You should see a similar result like this one below:

Image Result from While Loop

An example of the Foreach loop function

  • Use the Foreach loop to start a succession of values in a collection consisting of values.

  • Here’s an example script that features the ForEach loop.

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
$db = new MongoDB\Driver\Manager("mongodb://localhost:27017");

$db = $con->abi_db;
$collection = $db->subjects;
$cursor = $collection->find();


echo "

# "
. "For Each Loop Sample" . "

"
;

foreach($cursor as $row){

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

----------

"
;

}
  • Here is the result for the ForEach loop sample shown above.

Image Result from ForEach Loop

Conclusion

When you use loops, you make your data retrieval more relevant to your needs. We showed some example scripts of the While loop and Foreach loop. Test them out for yourself to get a feel for each method. You completed a short lesson about looping through MongoDB query results using PHP. The concept of loops is fundamental. Get creative with it in your scripting for all of your projects.

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.