PHP 和 MongoDB - 记录排序


执行任何操作的第一步是创建一个 Manager 实例。

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

第二步是准备并执行查询对象以选择集合中的记录并向其传递过滤器和选项以对记录进行排序。

$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);

例子

尝试以下示例来限制 MongoDB 服务器中的搜索结果 -

将以下示例复制并粘贴为 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";
   }
?>

输出

访问部署在 apache Web 服务器上的 mongodb_example.php 并验证输出。

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