CakeFest 2017 NYC, the Official CakePHP Conference

Persistent Connections (version 1.3.0+)

All versions of the driver since 1.3.0 utilize persistent connections to minimize the number of connections made to each database server. These connections are saved by the PHP worker process and may be reused between multiple requests.

Before connecting to a database server, the driver will create a hash for the connection based on its host, port, replica set name (if any), any authentication credentials (e.g. username, password, database), and the process ID. If a connection already exists for that hash, it will be used in lieu of creating a new connection associated with that hash. MongoClient::getConnections() may be used to retrieve info about each persistent connection. Consider the following program:


= new MongoClient('mongodb://localhost');
$m2 = new MongoClient('mongodb://localhost');
$m3 = new MongoClient('mongodb://user:pw@localhost');
$m4 = new MongoClient('mongodb://');
$m5 = new MongoClient('mongodb://rs1.local:30017,rs2.local:30018/?replicaSet=rs');
$m6 = new MongoClient('mongodb://sharding.local:40017');

foreach (
MongoClient::getConnections() as $conn) {
$conn['hash'], "\n";


The above example will output something similar to:


In this example $m1 and $m2 have the same hash and share a persistent connection. Connections for each other MongoClient instance hash to unique values and use their own sockets. Note that "localhost" and "" do not share the same hash; DNS resolution is not taken into account.

add a note add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top