'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 1:[1]

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().primary returns the current primary member
  • db.hostInfo().system.hostname returns the member where you are currently connected to

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Wernfried Domscheit