douqianxian7008 2015-06-25 22:12
浏览 67

用于PHP语言的MongoDB数据库中的分页

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条回答 默认 最新

  • douliaodun9153 2015-06-26 00:04
    关注

    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)}})
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大