PHP connection to MongoDB replica set fails after the primary node is removed.
I have built a mongodb replica set with five nodes; mongo1 is primary and the others are all secondary.
Here is my connection code:
$dbmongo_name = "myDatabase";
$dbmongo_conn_str = "mongodb://myusername:mypassword@mongo1.mysite.net:27017,mongo2.mysite.net@27017,mongo3.mysite.net@27017,mongo4.mysite.net@27017,mongo5.mysite.net@27017";
$dbmongo_conn_options = array("db" => $dbmongo_name, "replicaSet" => "rs1", "readPreference" => "secondaryPreferred", "connectTimeoutMS" => 5000);
class DB_Mongo {
global $dbmongo_conn_str, $dbmongo_conn_options;
public $connection;
function __construct() {
$this->connection = new MongoClient($dbmongo_conn_str, $dbmongo_conn_options);
}
}
I found that whenever I stop the service of the first server in the connection string (in this time, it is mongo1), php driver will either throw connection exception error or wouldn't throw any error but the "connected" property of the connection object would be false.
It seems that php driver couldn't connect to the replica set properly.
I have tried another experiment, swapping the position of the servers. This time my connection string is:
$dbmongo_conn_str = "mongodb://myusername:mypassword@mongo3.mysite.net:27017,mongo2.mysite.net@27017,mongo1.mysite.net@27017,mongo4.mysite.net@27017,mongo5.mysite.net@27017";
In this case mongo1 is still the primary; the error happens again when I stop the mongo3 service. It seems that everything would be OK as long as I don't stop the service of the first server in the list.