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?

chridam
  • 100,957
  • 23
  • 236
  • 235
mrana
  • 1,008
  • 3
  • 10
  • 16

1 Answers1

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)}})
anhlc
  • 13,839
  • 4
  • 33
  • 40