PHP & MongoDB Examples
- PHP & MongoDB - Connect Database
- PHP & MongoDB - Show Databases
- PHP & MongoDB - Drop Database
- PHP & MongoDB - Create Collection
- PHP & MongoDB - Drop Collection
- PHP & MongoDB - Display Collections
- PHP & MongoDB - Insert Document
- PHP & MongoDB - Select Document
- PHP & MongoDB - Update Document
- PHP & MongoDB - Delete Document
- PHP & MongoDB - Embedded Documents
- PHP & MongoDB - Error Handling
- PHP & MongoDB - Limiting Records
- PHP & MongoDB - Sorting Records
PHP & MongoDB Useful Resources
PHP & MongoDB - Overview
PHP developer team has provided MongoDB Driver for PHP and have various resources available for it.
First step in connecting to MongoDB using PHP is to have mongodb PHP driver dll in php ext directory and enable it in php.ini and then use mongodb API to connect to the database.
Connecting to MongoDB database
Suppose, MongoDB is installed locally and using default port then following syntax connects to MongoDB database.
$uri = "mongodb://localhost:27017"; // connect to mongodb $client = new MongoDB\Client($uri); echo "Connection to database successful.
";
MongoDB Driver Manager is the central class to do all the operations on mongodb database. To connect to mongodb database, we connect to database by first preparing a command and then executing it.
<?php
require __DIR__ . '\vendor\autoload.php';
$uri = "mongodb://localhost:27017";
// connect to mongodb
$client = new MongoDB\Client($uri);
echo "Connection to database successful.<br/>";
// select a database
$db = $client->myDb;
$stats=$db->command(array('dbStats' => 1));
// Convert the cursor to an array and get the first result document
$statistics = $stats->toArray()[0];
// Output the statistics
echo "Database Statistics:\n";
print_r($statistics)
?>
Once command is executed, if mydb database is not present, it will be created otherwise, it will be connected.
Output
Connection to database successful. Database Statistics: 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] => 157193351168 [fsTotalSize] => 295202451456 [ok] => 1 ) )
Advertisements