Error implementing simple Pagination with skip() a

2019-08-19 05:40发布

问题:

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);

?>