How to Sort Queries in MongoDB Using PHP

Introduction

If you’re a PHP developer working with MongoDB, you know that sometimes you want the results of a query returned in a specific order. For example, let’s say you’re querying a collection of student information– you may want to return a list of student names sorted alphabetically, or you may want the results returned in order of age. Regardless of your specific requirements, it’s easy to return your MongoDB query results in whatever order you need. In this article, we’ll explain how to sort queries in MongoDB using PHP.

Prerequisites

Before we begin looking at the actual code needed to sort queries, it’s important to ensure certain prerequisites are in place. For this task, there are a few key system requirements:

  • First, you need to ensure that both MongoDB and the MongoDB PHP driver are properly configured beforehand.

  • To determine if the MongoDB driver is installed, use the following command in a terminal window:

pecl search mongo
  • You’ll receive output that should look like the following:
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’ll also need to have PHP installed and running. To check what version of PHP is installed on your system, use the command shown below:
php --version
  • The output you receive should look something like this:
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 confirmed that all the system requirements are in place, the next step will be to start up the MongoDB database daemon. You’ll need to open a terminal window, which can be accomplished by pressing Ctrl + Alt + T. Then, you can start the MongoDB service and check the status using the command shown below. It’s a good idea to use the sudo command to avoid any permission-related issues while starting the MongoDB service:

sudo systemctl start mongod
sudo systemctl status mongod
  • After starting the service, you should 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)

Sort Techniques Using MongoDB Sort Command

Ascending Sorting using sort

Now that we’ve started up MongoDB, we’re ready to dive into the PHP code. Our first example will demonstrate how to sort results in ascending order. The script shown below sorts the documents in ascending order by the position field:

//Using MongoDB\Driver\Manager
global $db;
$filter = [];
$options = ['sort' => ['position' => 1]];
$query = new MongoDB\Driver\Query($filter,$options);
$result = $db->executeQuery("abi_db.subjects", $query);

// PHP Library
$filter = [];
$options = ['sort' => ['position' => 1]];
$db = $con->abi_db;
$collection = $db->subjects;
$result = $collection->find($filter,$options);

In the code above, note that we’re using the $option parameter within the query to specify the sort order. We then pass the parameters along with the query to MongoDB.

The results should look something like this:

record ascending order

Descending Sorting using sort

Our next example will demonstrate sorting results in descending order. You’ll see that it’s very similar in structure to the previous example. The script shown below will sort the documents in descending order by the position field:

//Using MongoDB\Driver\Manager
global $db;
$filter = [];
$options = ['sort' => ['position' => -1]];
$query = new MongoDB\Driver\Query($filter,$options);
$result = $db->executeQuery("abi_db.subjects", $query);

// PHP Library
$filter = [];
$options = ['sort' => ['position' => -1]];
$db = $con->abi_db;
$collection = $db->subjects;
$result = $collection->find($filter,$options);

The output from the above script will look something like this. You can see that the results were correctly sorted in descending order:

Image from Gyazo

Conclusion

When you’re querying MongoDB from a PHP script, there are times when you’ll want your results returned in a specific order. Whether you’re sorting cars by model year or returning a list of names in alphabetical order, it’s easy to sort your MongoDB query results with just a bit of simple code. Try experimenting with the sort parameters to see the different ways that data can be sorted and returned. With the instructions provided in this tutorial, you’ll have no trouble sorting queries in MongoDB using a PHP script.

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.