PHP & MongoDB - Limit Records



Steps to Limit Documents Selection in a collection

First step to do any operation is to create a MongoDB Client instance.

$uri = "mongodb://localhost:27017";
// connect to mongodb
$client = new MongoDB\Client($uri);

Second step is to prepare and execute a filter to select a document and select document using find() command while passing an option to limit records to 2.

// select a collection of a database
$collection = $client->selectCollection('myDb', 'sampleCollection');

// Define a Filter to select all records
$filter = [];

// Define a option to limit Records
$options = ['limit' => 2];

// execute the query
$cursor = $collection->find($filter, $options);

// Iterate over the cursor to access each document
foreach ($cursor as $document) {
   echo "<pre>"; 
   echo json_encode($document, JSON_PRETTY_PRINT);
   echo "</pre>";
}

Example - Limiting Documents Selection from a MongoDB Collection

Try the following example to limit documents from a MongoDB collection −

index.php

<?php
   require __DIR__ . '\vendor\autoload.php';
   $uri = "mongodb://localhost:27017";

   // connect to mongodb
   $client = new MongoDB\Client($uri);

   // select a collection of a database
   $collection = $client->selectCollection('myDb', 'sampleCollection');

   // Define a Filter to select all records
   $filter = [];

   // Define a option to limit Records
   $options = ['limit' => 2];

   // execute the query
   $cursor = $collection->find($filter, $options);
   
   // Iterate over the cursor to access each document
   foreach ($cursor as $document) {
      echo "<pre>"; 
      echo json_encode($document, JSON_PRETTY_PRINT);
      echo "</pre>";
   }
?>

Output

Access the index.php deployed on apache web server and verify the output.

{
    "_id": {
        "$oid": "696cf16bfed319cd950058d4"
    },
    "First_Name": "Mahesh",
    "Last_Name": "Parashar",
    "Date_Of_Birth": "1990-08-21",
    "e_mail": "mahesh_parashar.123@gmail.com",
    "phone": "9034343345"
}
{
    "_id": {
        "$oid": "696cf16bfed319cd950058d5"
    },
    "First_Name": "Radhika",
    "Last_Name": "Sharma",
    "Date_Of_Birth": "1995-09-26",
    "e_mail": "radhika_sharma.123@gmail.com",
    "phone": "9000012345"
}
Advertisements