0

enter image description here

I've one primary host as mongo1.ppshein.net, secondary host as mongo1.ppshein.net and arbiter as mongo3.ppshein.net, and configured MongoDB replica as above shown in AWS EC2. And in each of MongoDB config file, bindIP is as its host name and App Server host.

To access that MongoDB replica from python, I thought I could be able to use following code-snippet,

>>> from pymongo import MongoClient
>>> db = MongoClient('mongodb://serverA:27017, serverB:27017, serverC:27017/?replicaSet=foo').db_name

But problem is if serverA is down/unhealthy, I'm not sure whether above code-snippet would be working properly or not. That's why I'm curious to know how to get primary host of MongoDB instead of adding multiple hosts in connection string?

PPShein
  • 13,309
  • 42
  • 142
  • 227

1 Answers1

1

Once you connect to a replica set the driver will always reconnect you to the primary if one can be elected (i.e. you have a quorum of nodes). the only reason you give a list of nodes in the argument is to prevent a situation where you are attempting to connect to a node that is down. if that node was down you would get a server timeout.

The full specification for the server discovery and monitoring protocol is here.

Joe Drumgoole
  • 1,268
  • 9
  • 9
  • above my code snippet, for example if `serverA:27017` is down, MongoDB will elect `serverB:27017` as primary host. At that time, `serverA:27017` will be useless in connection string so do I need to remove `serverA:27017` from connection string? – PPShein Apr 30 '19 at 13:58
  • The expectation is that all servers will eventually rejoin the replica set. If your program was being run once every minute for instance and you only specified 1 server there is a good chance that over time that server might be down when the program was run leading to a server timeout. Its just additional redundancy to specify more than one member of the replica set. – Joe Drumgoole May 01 '19 at 14:53