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.
To connect to a replica set Primary use the mongo shell
--host
option:For example:
Note: Since 3.4.x, you cannot specify the db after, when using --host or --port. Bug report: https://jira.mongodb.org/browse/SERVER-28072
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:
will connect to my_mongo_server1, it may just be yet another SECONDARY node.
But:
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.
You can use the "name/seed1,seed2,..." format:
This should give you a connection to whichever node is currently primary and handle failover okay. You can specify one or more seeds and it'll find the rest.
Note that (AFAIK) the shell does not allow you to route reads to secondaries with a replica set connection.
To the best of my knowledge, the mongo command line client will not accept seeds to forward you to the master node, because you may often want to actually operate on the secondary node rather than being forwarded.
However, once connected to any node in the RS, you can discover the RS topology via
rs.config()
ordb.isMaster()
. You could then use this information to reconnect to the primary node. Depending on your shell, you might be able to usemongo --eval "db.isMaster()['primary']"
to automatically connect to the master.I am using v3.4. Also new to mongodb stuff... Although the help info from "man mongo" suggests to use "--host replicaSet/host:port,host:port" url, it does not work for me. However, I can connect to my replicaSet according to official document, as below:
So I guess the man page of my mongo is outdated (I am using CentOS 7.3).
You can use the
--host
param to specify the replSet name and seed list, thenmongo
will automatically connect to the current primary host.example:
mongo --host rs0/1.example.com:27017,2.example.com:27017,3.example.com:27017 [dbname]