Geoffrey Gallaway Geoffrey Gallaway - 19 days ago 5
PHP Question

How can I tell which secondary the MongoDB PHP driver is reading from?

I am using the legacy MongoDB driver (1.6.x) to connect to a MongoDB (2.4.x) replicaset. I've got "?readPreference=secondary" in my connection string and two MongoDB secondaries on a replicaSet. My connection string includes all the servers:

mongodb://dev-mongo01:27017,dev-mongo02:27017,dev-mongo03:27017/?replicaSet=dev-mongo-replica&readPreference=secondary


I'd like to find out which secondary the read comes from both to verify the readPreference is working as expected and to calculate the secondary's replication delay. I've tried looking at MongoClient->getConnections(), MongoClient->getHosts(), "serversatus" and "replSetGetStatus" from the admin database but can't find anything that tells me which secondary is providing the data.

Answer

You can call $cursor->info() after you've iterated/read from the cursor to get a data structure which contains a host, port and connection_type_desc keys. The host and port keys specify which MongoDB server satisfied that particular query.

$cursor = $this->mongoclient->selectDB("test")->selectCollection("test")->find();
$cursor->rewind();
print_r($cursor->info()); //MongoDB Cursor Info

See http://php.net/manual/en/mongocursor.info.php

Comments