When connecting to mongo cluster do we need replicaSet option in connection URI like below
mongodb://db1.example.net:27017,db2.example.net:2500/?replicaSet=test
What happens if replicaSet option is not used but all the nodes are given in connection URI like below
mongodb://db1.example.net:27017,db2.example.net:2500/
What is the advantage of giving and not giving replicaSet in the connection URI for the above 2 cases.
CodePudding user response:
You should specify also the replicaSet.
If you don't specify the replicaSet then you still connect to the PRIMARY node. However, in case the PRIMARY becomes unavailable then your connection is lost. If you specify the replicaSet then the client will automatically re-connect to the new primary member.
You an play around and make test with these commands:
db.hello().primaryreturns the current primary memberdb.hostInfo().system.hostnamereturns the member where you are currently connected to
CodePudding user response:
It's always recommended to include the replicaSet in the MongoDB connection String URI Format as a best practice. Enabling this will help to explore much more options for better application connectivity.
Advantages of including replicaSet:
- Once enabled the client/driver will be aware of the all
other membersin the replica set. - If fail-over occurs client/driver
automatically connectsto next available member with zero downtime. - Using readConcern we can
scale the readsbetter with other replica members.
replicaSet=myRepl&readConcernLevel=majority
- To acknowledge all the write operation we can use
write concernalong with the URI
replicaSet=myRepl&w=majority&wtimeoutMS=5000
- We can enable the
connection timeoutto maintain a better connectivity.
replicaSet=test&connectTimeoutMS=200000
- Securing the application to use only
TLS/SSLencrypted connections.
replicaSet=myRepl&ssl=true
For better secured application support and connectivity always use the replicaSet on connection String URI.
