Search code examples
pythonmongodbpymongo

Pymongo how to set read_preference


How do we enable PyMongo to read from the nearest? This field db.read_preference is read-only now.

from pymongo import ReplicaSetConnection
from pymongo import ReadPreference

db = ReplicaSetConnection('localhost:27017', replicaSet='rs1')['my_db']
db.read_preference = ReadPreference.NEAREST
db.tag_sets = [{'secondaries': 1}]

Solution

  • You need to add it to the connection string, like so:

    db = ReplicaSetConnection('localhost:27017?readPreference=nearest', replicaSet='rs1')['my_db']
    

    Or

    db = MongoClient("myhost:27017", read_preference=ReadPreference.NEAREST, replicaSet='rs1')['my_db']
    

    For whatever reason the given syntax you're using fails, it seems it's the syntax supported for older Pymongo versions.