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:
Or
For whatever reason the given syntax you’re using fails, it seems it’s the syntax supported for older Pymongo versions.
Option 1(per connection):
Option 2(per query):
PyMongo ReadPreference can also be applied at database, collection or a query level (in addition to within Connection String URI and with the MongoClient).
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).