PHP & MongoDB - Show Databases



Steps to Show Databases

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 on admin database to show the list of databases available.

// select admin database
$db = $client->admin;

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

Example - Getting List of MongoDB Databases

Try the following example to get list of databases on a MongoDB server −

index.php

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

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

   // select admin database
   $db = $client->admin;

   // execute a command
   $cursor=$db->command(array('listDatabases' => 1));
      
   $databases = current($cursor->toArray());
   
   foreach ($databases->databases as $database) {    
      echo $database->name . "<br/>";
   }
?>

Output

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

admin
config
local
myDb
mydata
newdata
sampleDB
test
Advertisements