3

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}]
angelokh
  • 9,426
  • 9
  • 69
  • 139
  • So you gave up on https://stackoverflow.com/questions/71641226/redis-py-read-lowest-latency-or-nearest and are using mongo now or are those two different problems to be solved? – N1ngu Apr 12 '22 at 11:49

3 Answers3

2

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.

Tom Slabbaert
  • 21,288
  • 10
  • 30
  • 43
2

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).

prasad_
  • 12,755
  • 2
  • 24
  • 36
1

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)
R2D2
  • 9,410
  • 2
  • 12
  • 28