Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

If I'm writing an application which connects to mongodb then I can provide a seed list for a replicaset, and the driver will direct me to the master node, where I can run write commands.

How do I specify the seed list for a commandline mongo shell in order to conenct to a replicaset.

like image 921
Richard Warburton Avatar asked Dec 17 '12 10:12

Richard Warburton


People also ask

How does MongoDB connect to ReplicaSet?

To connect to a replica set deployment, specify the hostname and port numbers of each instance, separated by commas, and the replica set name as the value of the replicaSet parameter in the connection string. In the following example, the hostnames are host1 , host2 , and host3 , and the port numbers are all 27017 .

Where can I find ReplicaSet in MongoDB?

how do I find out the replica set name to use? On MongoDB Atlas project page, select the Deployment link on the left hand side menu. Under Processes tab, with Topology view you should see the replica set name (this should be the default view presented when you click on Deployment ).


2 Answers

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:27018 MongoDB shell version: v3.4.9 connecting to: mongodb://john.local:27019,john.local:27018/?replicaSet=rs1 2017-10-12T14:13:03.094+0000 I NETWORK  [thread1] Starting new replica set monitor for rs1/john.local:27019,john.local:27018 2017-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> db test rs1: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.

like image 144
Gianfranco P. Avatar answered Oct 11 '22 19:10

Gianfranco P.


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"

like image 29
Shemeshey Avatar answered Oct 11 '22 18:10

Shemeshey