To implement pagination using MongoDB in PHP with the `MongoDB\Collection::find()` method, you can utilize the `limit()` and `skip()` functions. This allows you to control how many documents are returned and which documents to skip based on the current page.
Here’s a step-by-step guide on how to achieve this:
1. Set Up Your MongoDB Connection:
First, ensure you have the MongoDB PHP library installed and set up your connection to the database.
require 'vendor/autoload.php'; // Include Composer's autoloader $client = new MongoDB\Client("mongodb://localhost:27017"); $collection = $client->yourDatabase->yourCollection;
2. Define Pagination Parameters:
You need to define the current page and the number of items per page. For example:
$currentPage = isset($_GET['page']) ? (int)$_GET['page'] : 1; // Get current page from URL $itemsPerPage = 10; // Number of items per page
3. Calculate Skip Value:
The `skip()` method will be used to skip the documents based on the current page.
$skip = ($currentPage - 1) * $itemsPerPage; // Calculate how many documents to skip
4. Fetch Paginated Results:
Use the `find()` method along with `limit()` and `skip()` to fetch the desired documents.
$cursor = $collection->find([], [ 'limit' => $itemsPerPage, 'skip' => $skip, 'sort' => ['_id' => 1] // Optional: sort by _id or any other field ]);
5. Display Results:
Iterate through the cursor to display the results.
foreach ($cursor as $document) { echo $document['_id'], ': ', $document['name'], ' '; // Adjust according to your document structure }
6. Create Pagination Links:
To navigate between pages, you can create links based on the total number of documents.
$totalDocuments = $collection->countDocuments(); // Get total number of documents $totalPages = ceil($totalDocuments / $itemsPerPage); // Calculate total pages for ($i = 1; $i <= $totalPages; $i++) { echo '' . $i . ''; }
Example Code
Here’s a complete example that combines all the steps:
require 'vendor/autoload.php'; $client = new MongoDB\Client("mongodb://localhost:27017"); $collection = $client->yourDatabase->yourCollection; $currentPage = isset($_GET['page']) ? (int)$_GET['page'] : 1; $itemsPerPage = 10; $skip = ($currentPage - 1) * $itemsPerPage; $cursor = $collection->find([], [ 'limit' => $itemsPerPage, 'skip' => $skip, 'sort' => ['_id' => 1] ]); foreach ($cursor as $document) { echo $document['_id'], ': ', $document['name'], ''; } $totalDocuments = $collection->countDocuments(); $totalPages = ceil($totalDocuments / $itemsPerPage); for ($i = 1; $i <= $totalPages; $i++) { echo '' . $i . ''; }
This code will allow you to paginate through your MongoDB collection effectively using PHP. Adjust the field names and database/collection names as necessary for your specific use case.