Pymongo how to set read_preference

Viewed 134

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}]
3 Answers

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.

PyMongo ReadPreference can also be applied at database, collection or a query level (in addition to within Connection String URI and with the MongoClient).

from pymongo import ReadPreference

# Specifying read preference at database level
db1 = client.testdb1
db2 = client.get_database('testdb2', read_preference=ReadPreference.NEAREST)

# Specifying read preference at collection level
coll2 = db1.coll1.with_options(read_preference=ReadPreference.NEAREST)

# Specifying read preference for a specific query
result = db1.coll1.with_options(read_preference=ReadPreference.NEAREST).find()

Note the read preference set at the lower level (e.g., collection) will override the one set at the previous level (e.g., database or mongo client).

Option 1(per connection):

>>> from pymongo import MongoClient, ReadPreference
>>> db = MongoClient("myhost:27017", read_preference=ReadPreference.NEAREST).test
>>> db.collection.find_one({test:1})

Option 2(per query):

>>> db.collection.find_one({test:1},read_preference=ReadPreference.NEAREST)
Related