How to handle pagination queries properly with mongodb and php?

后端 未结 2 879
庸人自扰
庸人自扰 2021-01-31 05:12

Am I doing this right? I went to look at some old PHP code w/ MySQL and I\'ve managed to get it to work, however I\'m wondering if there\'s a much \"cleaner\" and \"faster\" way

相关标签:
2条回答
  • 2021-01-31 06:00

    Since the result of find()->limit()->skip() is a Mongo_Cursor you don't have to execute the actual query twice.

    The following should work as well :

    $skip = (int)($docs_per_page * ($page - 1));
    $limit = $docs_per_page;
    
    $query = array("loc" => array('$near' => array('lat' => $latitude, 'lon' => $longitute) ),
        "tags" => $tag, "seeking" => $this->session->userdata('gender'),
        "gender" => $this->session->userdata('seeking'));
    
    $fields = array("username", "zipcode", "tags", "birth_date");
    $cursor = $collection->find($query, $fields)->limit($limit)->skip($skip);
    $total_documents = $cursor->count();
    $data['result'] = $cursor;
    

    btw I first misread your question, I thought you didn't know about limit & skip.

    0 讨论(0)
  • 2021-01-31 06:08

    Yes you are doing right. And you can run query in one shot.

    Here is a paging example:

    function printStudents(pageNumber, nPerPage) {
       print("Page: " + pageNumber);
       db.students.find().skip((pageNumber-1)*nPerPage).limit(nPerPage).forEach( function(student) { print(student.name + "<p>"); } );
    }
    

    Reference: Advanced Queries - MongoDB: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-{{skip%28%29}}

    0 讨论(0)
提交回复
热议问题