PHP & MongoDB - Connect Database



Steps to Connect MongoDB Database

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 a database if the database doesn't exist then MongoDB creates it automatically.

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

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

Example - Connecting MongoDB Database and Printing Database Statistics

Try the following example to connect to a MongoDB server −

index.php

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

   // connect to mongodb
   $client = new MongoDB\Client($uri);
   echo "Connection to database successfully";

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

   // execute a command
   $cursor=$db->command(array('dbStats' => 1));
      
   $statistics = current($cursor->toArray());
   echo "<pre>"; 
   print_r($statistics); 
   echo "</pre>";
?>

Output

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

Connection to database successfully
MongoDB\Model\BSONDocument Object
(
    [storage:ArrayObject:private] => Array
        (
            [db] => myDb
            [collections] => 4
            [views] => 0
            [objects] => 7
            [avgObjSize] => 58
            [dataSize] => 406
            [storageSize] => 81920
            [indexes] => 4
            [indexSize] => 81920
            [totalSize] => 163840
            [scaleFactor] => 1
            [fsUsedSize] => 158140493824
            [fsTotalSize] => 295202451456
            [ok] => 1
        )

)
Advertisements