How do you connect to a replicaset from a MongoDB shell? How do you connect to a replicaset from a MongoDB shell? mongodb mongodb

How do you connect to a replicaset from a MongoDB shell?


To connect to a replica set Primary use the mongo shell --host option:

mongo --host replicaSetName/host1[:porthost1],host2[:porthost1],host3[:porthost3],etc

For example:

$ mongo --host rs1/john.local:27019,john.local:27018MongoDB shell version: v3.4.9connecting to: mongodb://john.local:27019,john.local:27018/?replicaSet=rs12017-10-12T14:13:03.094+0000 I NETWORK  [thread1] Starting new replica set monitor for rs1/john.local:27019,john.local:270182017-10-12T14:13:03.096+0000 I NETWORK  [thread1] Successfully connected to john.local:27019 (1 connections now open to john.local:27019 with a 5 second timeout)2017-10-12T14:13:03.096+0000 I NETWORK  [thread1] Successfully connected to john.local:27018 (1 connections now open to john.local:27018 with a 5 second timeout)rs1:PRIMARY> dbtestrs1:PRIMARY>

Note: From versions 3.4.2 to 3.4.10 there was a bug (SERVER-28072) which prevented specifying the db after when using --host or --port.


The answers above are for Mongo 3.2.

According to Mongo 3.4 documentation, the shell was changed a bit:

In 3.2:
mongo --host host1,host2,host3/myRS myDB
or,
mongo --host host1:27017,host2:27017,host3:27017/myRS myDB

In 3.4:
mongo "mongodb://host1,host2,host3/myDB?replicaSet=myRS"
or,
mongo "mongodb://host1:27017,host2:27017,host3:27017/myDB?replicaSet=myRS"


All you have to do is to use --host and give it one of your hosts in the replicaset but with the name of the replicaset as a prefix.

For example:

mongo --host my_mongo_server1

will connect to my_mongo_server1, it may just be yet another SECONDARY node.

But:

mongo --host my_repl_set_name/my_mongo_server1

will always connect to the PRIMARY node in the replica set, even if it's not my_mongo_server1.

Why? The answer is "replica set monitor".In the example above, mongo shell would connect to the specified node, start a new replica set monitor for the replica set and will use the specified node just to seed it. From there, the monitor will figure out all nodes in the replica set and will switch the connection to the PRIMARY node.

Hope that helped.