0

I have the following code for the pagination(PHP) in MongoDB database.

        <?php
    $mongodb    = new Mongo("vvv");
    $database   = fff
    $collection = gggg

    $page  = isset($_GET['page']) ? (int) $_GET['page'] : 1;
    $limit = 12;
    $skip  = ($page - 1) * $limit;
    $next  = ($page + 1);
    $prev  = ($page - 1);
    $sort  = array('createdAt' => -1);   
    $cursor = $collection->find()->skip($skip)->limit($limit)->sort($sort);
    foreach ($cursor as $r) {
        --------
    } 
$total= $cursor->count(); 
    if($page > 1){
        echo '<a href="?page=' . $prev . '">Previous</a>';
        if($page * $limit < $total) {
            echo ' <a href="?page=' . $next . '">Next</a>';
        }
    } else {
        if($page * $limit < $total) {
            echo ' <a href="?page=' . $next . '">Next</a>';
        }
    }

    $mongodb->close();
    ?>

BUT my database size is 30GB+, each search provides the results of 20,000 which takes HUGE TIME to count() //$total= $cursor->count(); Can any one provide any PHP pagination code for MongoDB which does not count the total number of results but do the pagination?

1

1 Answer 1

0

cursor.skip() requires the server to walk from the beginning of the collection or index to get the offset or skip position before beginning to return results. It is not recommended to use it in pagination against 30GB+ data in your case.

If you cannot narrow a little bit your condition in find(), you can consider to add a sequence number in your docs for pagination purpose, assuming that you will rarely remove/update those documents:

{
 createdAt: "2015-01-01",
 ... 
 seq_no: 1
},
{
  createdAt: "2015-01-02",
 ... 
 seq_no: 2
}

Then you can implement the pagination query like this (remember to create the index on seq_no, of course):

$cursor = $collection->find({"seq_no": {"$gt":$skip, "$lte":($skip+$limit)}})
3
  • if i apply your code its giving me error in the php editor. does not work!! any other way to do it?
    – mrana
    Commented Jun 27, 2015 at 21:14
  • sorry, my bad, just wrap "seq_no" "$gt" "$lte" with quotes
    – anhlc
    Commented Jun 28, 2015 at 23:29
  • yes thanks, following code is the solution: $sort = array('createdAt' => -1);
    – mrana
    Commented Jun 30, 2015 at 18:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.