title: MongoDB check connection of replica member before connecting with Java driver
body: <p>I am implementing a feature in Java to check the status of the replica set. To do that, I have to connect to one member of the replica set. I extracted the information of each replica set from mongos and stored them in an array, from that array I can get the uri of all replica members.  The problem is that I don't know how to detect if that uri works or not before connecting to it. Currently, I am doing this:</p>
  
  <pre><code>MongoClient shard = new MongoClient(Arrays.asList(
                  new ServerAddress(replicaUriTemp[0]),
                  new ServerAddress(replicaUriTemp[1]),
                  new ServerAddress(replicaUriTemp[2])));
  </code></pre>
  
  <p>When I stop two replica members [0] and [1], the program cannot connect to [2] and perform the replSetGetStatus command. It always throws this exception:</p>
  
  <pre><code>MongoTimeoutException: A server error occurred: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=REPLICA_SET, servers=[{address=dockerbox:21100, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}, {address=dockerbox:21200, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}, {address=dockerbox:21300, type=REPLICA_SET_SECONDARY, roundTripTime=1.0 ms, state=CONNECTED}]
  </code></pre>
  
  <p>However, it works fine when I try to connect to replica member [2] directly:</p>
  
  <pre><code>MongoClient shard = new MongoClient(new ServerAddress(replicaUriTemp[2]));
  </code></pre>
  
  <p>Is there a way to resolve this matter by connecting to each replica member dynamically, or ping the member before attempting to connect to it ?  I want to blindly test status of replica set without knowing in advance which one is primary/secondary member.</p>
  
  <p><strong>Edit:</strong> Seems like the error appears in the my next line of code:</p>
  
  <pre><code>Document replStatus = shard.getDatabase("admin").runCommand(replStatCmd);
  </code></pre>
  
  <p>Since I turn off two replica members, the left one will become a secondary and that's why I cannot perform runCommand on this member. </p>