pymongo replication secondary readreference not wo

2019-07-21 10:05发布

问题:

we have MongoDB 2.6 and 2 Replica Set, and we use pymongo driver and connect Mongo Replicat Set with the following url

mongodb://admin:admin@127.0.0.1:10011:127.0.0.1:10012,127.0.0.1:10013/db?replicaSet=replica

with python code

from pymongo import MongoClient
url = 'mongodb://admin:admin@127.0.0.1:10011:127.0.0.1:10012,127.0.0.1:10013/db?replicaSet=replica'
db = 'db'
db = MongoClient(
    url,
    readPreference='secondary',
    secondary_acceptable_latency_ms=1000,
)[db]
db.test.find_one()
# more read operations

but it turns out that the connection didn't read anything from secondary replicat set, no connection log could be found in mongo log on these 2 secondary replica set

回答1:

Try to configure a ReplicaSetConnection instead. For instance:

>>> db = ReplicaSetConnection("morton.local:27017", replicaSet='foo').test
>>> from pymongo import ReadPreference
>>> db.read_preference = ReadPreference.SECONDARY