PHP 和 MongoDB - 对记录排序



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

// Connect to MongoDB using Manager Instance
$manager = new MongoDB\Driver\Manager("mongodb://127.0.0.1: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://127.0.0.1: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.
广告