PHP & MongoDB - Sorting Records



First step to do any operation is to create a Manager instance.

// Connect to MongoDB using Manager Instance
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

Second step is to prepare and execute a Query object to select record(s) in the collection and pass it filters and options to sort the records.

$filter = [];

// Sort in Descending Order, For ascending order pass 1
$options = ['sort' => ['First_Name' => -1]];
// Create a Query Object
$query = new MongoDB\Driver\Query($filter, $options);

// Execute the query
$rows = $manager->executeQuery("testdb.sampleCollection", $query);

Example

Try the following example to limit search results in MongoDB server −

Copy and paste the following example as mongodb_example.php −

<?php
   try {
      // connect to mongodb
      $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

      $filter = [];
      $options = ['limit' => 3, 'sort' => ['First_Name' => -1]];

      // Create a Query Object
      $query = new MongoDB\Driver\Query($filter, $options);

      // Execute the query
      $rows = $manager->executeQuery("myDb.sampleCollection", $query);

      foreach ($rows as $row) {  
         printf("First Name: %s, Last Name: %s.<br/>", $row->First_Name, $row->Last_Name);   
      }
   } catch (MongoDB\Driver\Exception\Exception $e) {	   
      echo "Exception:", $e->getMessage(), "\n";
   }
?>

Output

Access the mongodb_example.php deployed on apache web server and verify the output.

First Name: Radhika, Last Name: Sharma.
First Name: Rachel, Last Name: Christopher.
First Name: Fathima, Last Name: Sheik.
Advertisements