Php Mongodb 简明教程
PHP & MongoDB - Sorting Records
执行任何操作的第一步是创建一个管理器实例。
// Connect to MongoDB using Manager Instance
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
第二步是准备并执行一个 Query 对象以选择集合中的记录,并传递筛选器和选项以对记录进行排序。
$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
尝试以下示例以限制 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";
}
?>