PHP & MongoDB - Display Collections



Steps to Display a List of Collections

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 command to get list of collections.

// select a database
$db = $client->myDb;

// execute a command
$cursor=$db->command(array('listCollections' => 1));

Example - List MongoDB Collections

Try the following example to list collections of a MongoDB database −

index.php

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

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

   // select a database
   $db = $client->myDb;
   
   // create a collection
   $cursor=$db->command(array('create' => 'sampleCollection'));
   
   // execute a command
   $cursor=$db->command(array('listCollections' => 1));
      
   $collections = $cursor->toArray();
   
   foreach ($collections as $collection) {    
      echo $collection->name . "<br/>";
   }
?>

Output

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

sampleCollection
Advertisements