使用MongoDB PHP驱动程序和相关PHPLib库中的skip()和limit()实现简单分页时出错

时间:2017-11-24 10:44:46

标签: php mysql mongodb pagination phplib

我正在尝试使用PHP从MongoDB访问数据时实现分页。在MySQL中,我会使用 OFFSET LIMIT 。我的谷歌搜索告诉我,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;
}

?>

1 个答案:

答案 0 :(得分:0)

尝试使用它:

<?php 

$filter = [];
$options = [
    'limit' => 25,
    'skip' => 25
];

$allDataCursor = $collection->find($filter, options);

?>