在 MongoDB PHP 驱动程序和相关 PHPLib 库中使用 skip() 和 limit() 实现简单分页时出错
Error implementing simple Pagination with skip() and limit() in MongoDB PHP driver and related PHPLib library
我正在尝试在使用 PHP 从 MongoDB 访问数据时实现分页。在 MySQL 中,我会使用 OFFSET
和 LIMIT
。我的 Google 搜索告诉我 PHP-MongoDB 的备选方案是 skip()
和 limit()
.
但是当我尝试使用这些函数时,出现致命错误。这是错误:
Fatal error: Uncaught Error: Call to undefined method MongoDB\Driver\Cursor::skip() in /var/www/html/Tests/test_mongo_two/test.php:12 Stack trace: #0 {main} thrown in /var/www/html/Tests/test_mongo_two/test.php on line 12
以下是演示问题的示例 (SSCCE)。问题是我哪里出错了?我错过了什么?我该如何解决这个问题?
<?php
require 'vendor/autoload.php';
$connection = new MongoDB\Client("mongodb://localhost:27017");
$db = $connection->Traffic;
$collection = $db->frameLengthsCollection;
#$allDataCursor = $collection->find();
$allDataCursor = $collection->find()->skip(25)->limit(25);
#$allDataCursor = $allDataCursor->limit(25);
#$allDataCursor = $allDataCursor->skip(25);
/**
* Prettifying (is that a word?) of data
*/
$allDataCursorConvertedToArray = array();
foreach ($allDataCursor as $key => $value) {
$json = MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($value));
$allDataCursorConvertedToArray[] = json_decode($json, true);
}
/**
* Display!
*/
#echo "allDataCursorConvertedToArray: "; print_r($allDataCursorConvertedToArray); echo "<br><br>";
//
foreach ($allDataCursorConvertedToArray as $key => $value) {
print_r($value);
break;
}
?>
尝试使用这个:
<?php
$filter = [];
$options = [
'limit' => 25,
'skip' => 25
];
$allDataCursor = $collection->find($filter, options);
?>
我正在尝试在使用 PHP 从 MongoDB 访问数据时实现分页。在 MySQL 中,我会使用 OFFSET
和 LIMIT
。我的 Google 搜索告诉我 PHP-MongoDB 的备选方案是 skip()
和 limit()
.
但是当我尝试使用这些函数时,出现致命错误。这是错误:
Fatal error: Uncaught Error: Call to undefined method MongoDB\Driver\Cursor::skip() in /var/www/html/Tests/test_mongo_two/test.php:12 Stack trace: #0 {main} thrown in /var/www/html/Tests/test_mongo_two/test.php on line 12
以下是演示问题的示例 (SSCCE)。问题是我哪里出错了?我错过了什么?我该如何解决这个问题?
<?php
require 'vendor/autoload.php';
$connection = new MongoDB\Client("mongodb://localhost:27017");
$db = $connection->Traffic;
$collection = $db->frameLengthsCollection;
#$allDataCursor = $collection->find();
$allDataCursor = $collection->find()->skip(25)->limit(25);
#$allDataCursor = $allDataCursor->limit(25);
#$allDataCursor = $allDataCursor->skip(25);
/**
* Prettifying (is that a word?) of data
*/
$allDataCursorConvertedToArray = array();
foreach ($allDataCursor as $key => $value) {
$json = MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($value));
$allDataCursorConvertedToArray[] = json_decode($json, true);
}
/**
* Display!
*/
#echo "allDataCursorConvertedToArray: "; print_r($allDataCursorConvertedToArray); echo "<br><br>";
//
foreach ($allDataCursorConvertedToArray as $key => $value) {
print_r($value);
break;
}
?>
尝试使用这个:
<?php
$filter = [];
$options = [
'limit' => 25,
'skip' => 25
];
$allDataCursor = $collection->find($filter, options);
?>