I adopted pymongo's MongoClient class to do connect to a replicaset which has three node, 1 primary 2 secondary. The code snippet as following:
c = MongoClient([secondary1_hostname, secondary2_hostname], replicaSet='rs0')
When check the three mongod's log, I found there is always a connection created to the primary host, but other 2 secondary not received the connection request from client or got connection immediately disconnected. Seems the client first reached one secondary got the primary address then dropped the connection and created long-term connection to primary.
However, when I use MongoReplicaSetClient class, with the follwing code sinppet:
c = MongoReplicaSetClient(secondary1_name, replicaSet='rs0')
There are always 3 connection created to each replica set member, got from the mongod's log file.
So, why the behavior of MongoClient is always only create connection to the primary? I read the manual of PyMongo, but didn't find the answer. Any suggestion is appreciated.
MongoClient
is for single connections only, and when speaking toMongoD
it will chose the last in the list of databases. When adding areplicaSet
pymongo it will verify that the replica set it connects to matches this name. Implies that the hosts specified are a seed list and pymongo should attempt to find all members of the set, then it will connect to the Primary node.Another reason
MongoClient
accepts multiple hosts is for handlingMongos
and high availability: http://api.mongodb.org/python/current/examples/high_availability.html#high-availability-and-mongosMongoClient
also handles replicaset configurations for when speaking to a replicaSet via Mongos.MongoReplicaSetClient
is specifically for replicaset connections, it attempts to find all members of the set. It also launches the replica-set monitor, which allows it to quickly respond to changes in replica set configuration.The
MongoClient
class only connects to a single host, as the documentation (http://api.mongodb.org/python/current/api/pymongo/mongo_client.html) says:You need to use the
MongoReplicaSetClient
class that you've already discovered to work with a Replica Set.With current pymongo (=3.2):
As explained in pymongo high availability documentation: