How do I ensure I always connect to Primary/Secondary node in a MongoDB ReplicaSet? I have a 3 node replica set running on 3 different servers. I have finished setting it up and everything works great. Now I want to give my users two connection strings:


Connect to this "xyz" for write 
Connect to this "abc" for read only traffic


I am also trying to set up a CNAME for each of the connections, to be able to have the flexibility to change in the future.

Thanks and appreciate your time in advance.
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.