Search code examples
mongodbpymongo

Do we need replicaSet in connection URI of MongoDB


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.


Solution

  • 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:

    1. Once enabled the client/driver will be aware of the all other members in the replica set.
    2. If fail-over occurs client/driver automatically connects to next available member with zero downtime.
    3. Using readConcern we can scale the reads better with other replica members.

    replicaSet=myRepl&readConcernLevel=majority

    1. To acknowledge all the write operation we can use write concern along with the URI

    replicaSet=myRepl&w=majority&wtimeoutMS=5000

    1. We can enable the connection timeout to maintain a better connectivity.

    replicaSet=test&connectTimeoutMS=200000

    1. Securing the application to use only TLS/SSL encrypted connections.

    replicaSet=myRepl&ssl=true

    For better secured application support and connectivity always use the replicaSet on connection String URI.