Connecting
Connecting to MongoDB can be as easy as new Mongo, but there are many additional options and configurations. The Mongo::__construct() page covers all of the API options, but this page gives some more practical use cases.
Logging In on Connection
If MongoDB is started with the --auth option, connections must be authenticated before they are used. You can do this on a per-database level with MongoDB::authenticate():
<?php
$m = new Mongo();
$db = $m->admin;
$db->authenticate($username, $password);
?>
There is a major disadvantage to this method: if the database connection is dropped and then reconnected, the connection will no longer be authenticated.
If you use the connection string format described by Mongo::__construct(), the database will authenticate on connection and reauthenticate if the connection is re-established.
This is equivalent to the code above, except that reconnections to the database will be authenticated automatically:
<?php
$m = new Mongo("mongodb://${username}:${password}@localhost");
?>
By default, the driver will authenticate the user against the admin database. To authenticate with a different database, specify the database name after the hosts. This example will log the user into the "blog" database:
<?php
$m = new Mongo("mongodb://${username}:${password}@localhost/blog");
?>
Replica Sets
To connect to a replica set, specify one or more members of the set and use the replicaSet option.
<?php
$m = new Mongo("mongodb://localhost:27017", array("replicaSet" => true));
?>
Version 1.0.9+ of the driver is required to connect to a replica set (earlier versions of the driver will not autodetect the master or reconnect correctly).
The PHP driver will query the database server(s) listed to figure out who is master. So long as it can connect to at least one host listed and find a master, the connection will succeed. If it cannot make a connection to any servers listed or cannot find a master, a MongoConnectionException will be thrown.
If the master becomes unavailable, the slaves will not promote a new master for a few seconds. During that time, this connection will not be able to perform any database operations (connections to slaves will still be able to perform reads). Thus, if you attempt to do any sort of read or write on this connection, it will throw an exception.
Once a master is elected, attempting to perform a read or write will allow the driver to detect the new master. The driver will make this its primary database connection and continue operating normally.
For more information on replica sets, see the » core documentation.
Distributing Reads
One way of using replica sets is to perform reads on the slaves to take some load off of the master. The driver will not do this automatically for you, but you can set it up yourself.
First, connect to the replica set using the replicaSet option. This will give you a connection to the replica set's master. Use this connection to call the ismaster command, which lists all of the slaves in the replica set.
<?php
$m = new Mongo("mongodb://localhost:27017", array("replicaSet" => true));
$result = $m->admin->command(array("ismaster" => 1));
?>
Now, create connections to the hosts listed in the "hosts" and "passives" fields (passives are members of the set that can never become master). Do not use replicaSet => true, or the driver will automatically find and use the master.) Then you can distribute reads among these connections. Make sure to set MongoCursor::slaveOkay to TRUE before attempting to read from a slave.
Persistent Connections
Creating new connection to the database is very slow. To minimize the number of connections that you need to make, you can use persistent connections. A persistent connection is saved by PHP, so you can use the same connection for multiple requests.
For example, this simple program connects to the database 1000 times:
<?php
for ($i=0; $i<1000; $i++) {
$m = new Mongo();
}
?>
It takes approximately 18 seconds to execute. If we change it to use a persistent connection:
<?php
for ($i=0; $i<1000; $i++) {
$m = new Mongo("localhost:27017", array("persist" => "x"));
}
?>
...it takes less than .02 seconds to execute, as it only makes one database connection.
Persistent connections need an identifier string (which is "x" in the above example) to uniquely identify them. For a persistent connection to be used, the hostname, port, persist string, and username and password (if given) must match an existing persistent connection. Otherwise, a new connection will be created with this identifying information.
Persistent connections are highly recommended and should always be used in production unless there is a compelling reason not to. Most of the reasons that they are not recommended for relational databases are irrelevant to MongoDB.
Persistent connections will become the default connection type in 1.0.12. To create a non-persistent connection, you will need to pass "persist" => false to Mongo::__construct().
Domain Socket Support
If you are running MongoDB locally and have version 1.0.9 or better of the driver, you can connect to the database via file. MongoDB automatically opens a socket file on startup: /tmp/mongodb-<port>.sock.
To connect to the socket file, specify the path in your MongoDB connection string:
<?php
$m = new Mongo("mongodb:///tmp/mongo-27017.sock");
?>
If you would like to use authentication on connection (as described above) with a socket file, you must specify a port of 0 so that the connection string parser knows where the end of the connection string is.
<?php
$m = new Mongo("mongodb://username:password@/tmp/mongo-27017.sock:0/foo");
?>