How do I ensure I always connect to Primary/Secondary node in a MongoDB ReplicaSet?
Ref: https://docs.mongodb.com/manual/reference/connection-string/

If you are using replica set you do not use your mongod hostname in your connecton string. Rather use all mongos hostname and replica set name.

As an example:


  To describe a connection to a replica set named test, with the
  following mongod hosts:
  
  db1.example.net on port 27017 and db2.example.net on port 2500. You
  would use a connection string that resembles the following:
  
  mongodb://db1.example.net,db2.example.net:2500/?replicaSet=test


Writes will always go to primary and you do not have to do anything. Config and mongos will communicate among themselves will redirect to primary.

You can configure Write concern which describes the kind of assurances that the mongod and the driver provide to the application regarding the success and durability of the write operation. For a full explanation of write concern and write operations in general, see Write Concern.

Read Preference Options

Read preferences describe the behavior of read operations with regards to replica sets. These parameters allow you to specify read preferences on a per-connection basis in the connection string. The default value is primary, which sends all read operations to the replica set’s primary.

The read preference values are the following:


primary
primaryPreferred
secondary
secondaryPreferred
nearest


For descriptions of each value, see Read Preference Modes.