Error implementing simple Pagination with skip() and limit() in MongoDB PHP driver and related PHPLib library

荒凉一梦 提交于 2019-12-11 17:47:52

问题


I am trying to implement pagination when accessing data from MongoDB using PHP. In MySQL, I would have used OFFSET and LIMIT. My Google search told me that the alternative of PHP-MongoDB is skip() and limit().

But when I try to use those functions, I get a fatal error. Here is the error:

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

Following is an example (SSCCE) demonstrating the problem. The question is that where am I going wrong? What am I missing? How do I fix this?

<?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:


Try to use this:

<?php 

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

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

?>


来源:https://stackoverflow.com/questions/47471570/error-implementing-simple-pagination-with-skip-and-limit-in-mongodb-php-driv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!