Same connection string to connect to any node of a replica set

Hi @Jaime_Martin and welcome in the MongoDB Community :muscle: !

First of all, if you want to learn more about MongoDB, you should check out the MongoDB University. It’s free and full of courses that will help you get up to speed with MongoDB. Given the context of your question, the M103 one should be just right for you.

Now to answer your question. MongoDB works with a Replica Set (RS) of, usually, 3 nodes. If you want to connect to the full replica set rather than just a single node, you have to connect with the full connection string. In your case it’s something like:

mongodb://localhost:27017,localhost27018,localhost:27019/myDatabase?replicaSet=myReplicaSetName

More about connection strings in the doc: https://www.mongodb.com/docs/manual/reference/connection-string/

If you connect with the replicaSet option, then the driver will retrieve the RS config and identify the Primary in the list of servers. We say that the drivers are “replica set aware”. It knows the entire topology so it can adapt in case another nodes becomes Primary.

Sharded clusters are an entire different story. You use a sharded cluster when you want to split the workload across multiple RS working together (=shards). All the shards are then reached through mongos nodes (=routers) which are usually hosted near the drivers. Usually you use these when you have more than 2 TB of data.

Cheers,
Maxime.

1 Like