Manually Persistent Connections (version up to 1.1.4 *only*)

Notă:

This section is not relevant for 1.2.0+. In 1.2.0+, connections are always persistent and managed automatically by the driver. If you are using a 1.2.x release (but not 1.3.x or later), see MongoPool for more information on pooling.

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 MongoClient();
}

?>

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 MongoClient("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 authentication credentials (username, password and database, 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.