Connecting to and disconnecting from a MongoDB server in PHP
For the purpose of this demonstration, let's assume that we had installed a MongoDB server instance as a windows service which listens on port 12345. In addition, our PHP web server runs on the same machine as the MongoDB server.
Connecting to a MongoDB server
We can connect to the MongoDB server by specifying the server address and port in the standard connection string format and passing the string into the
<?php $connection = new Mongo('mongodb://localhost:12345'); ?>
Using some functions of the Mongo instance
Getting information about the databases managed by the MongoDB server
<?php $dbArray = $connection->listDBs(); echo '<pre>'; print_r($dbArray); echo '</pre>' ?>
listDBs function of the Mongo instance can be used to retrieve some information about the databases that are managed by the
MongoDB server that we had connected to. The return value is an array that resembles the following format:
Array ( [databases] => Array (  => Array ( [name] => admin [sizeOnDisk] => 83886080 [empty] => )  => Array ( [name] => techcoil [sizeOnDisk] => 83886080 [empty] => )  => Array ( [name] => local [sizeOnDisk] => 1 [empty] => 1 ) ) [totalSize] => 167772160 [ok] => 1 )
Gaining code access to a database instance
There are two ways which we can gain access to a database managed by the MongoDB server:
Via the selectDB function
<?php $techcoilDB = $connection->selectDB('techcoil'); ?>
Via the __get magic function
<?php $techcoilDB = $connection->techcoil; ?>
Both of the code segments retrieve an instance of
MongoDB that allow us to manipulate the "techcoil" database.
Gaining code access to a collection within a database instance
Apart from gaining code access to a database, the
Mongo class also contains the
selectCollection function which allows us to gain code access to a collection within the database.
<?php $userCollection = $collection->selectCollection("techcoil", "User"); ?>
The code segment retrieves a
MongoCollection instance and set it to the
$userCollection variable. We can then manipulate the "User" collection that is in the "techcoil" database via the
Disconnecting from a MongoDB server
To disconnect from the MongoDB server, we use the same variable which holds the Mongo instance that we had used for connection and execute its close function.
<?php $connection->close(); ?>