How do you connect to a replicaset from a MongoDB

2019-01-31 02:28发布

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.

9条回答
一纸荒年 Trace。
2楼-- · 2019-01-31 03:17

Building on the answer by Chris Heald these two bash aliases let me connect to the master with one command (where db1.test.test is one member of the replica set, acme is the database name, mreppy is my account etc) It will fail of course if db1 is down, but it's still handy.

alias whichprimary='mongo db1.test.test/acme --username mreppy --password testtest --quiet --eval "db.isMaster()['"'primary'"']"' 
alias connectprimary='mongo -u mreppy -p testtest `whichprimary`/acme'

The quoting in the eval alias is hard, I used How to escape single-quotes within single-quoted strings? for help :-)

查看更多
霸刀☆藐视天下
3楼-- · 2019-01-31 03:18

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"

查看更多
劫难
4楼-- · 2019-01-31 03:21

In the shell, you can first use:

mongo --nodb

to open a mongo session without connecting to mongo replicaset

Then, like kristina said, then you should be able to use

conn = new Mongo("myReplicaSet/A:27017,B:27017,C:27017")

to connect to a replicaset.

Or eventually put

conn = new Mongo("myReplicaSet/A:27017,B:27017,C:27017")

in your js file and

mongo --nodb yourcode.js
查看更多
登录 后发表回答