SETUP:
I have one PRIMARY and two SECONDARY instances of mongodb. One of the two secondary instances is hosted in the same region as my web app.
I am using pymongo for connecting.
QUERY:
How can I get connection to a SECONDARY with lower latency.
Currently I am doing this:
from pymongo import ReplicaSetConnection
from pymongo import ReadPreference
db = ReplicaSetConnection('localhost:27017', replicaSet='rs1')['my_db']
db.read_preference = ReadPreference.SECONDARY
I get a connection to any one of the SECONDARY. How can I force to get connection from the instance with lower latency
Thanks!!
The read preferences are as follows:
So theres no specific one for the nearest secondary. You could achieve this by combining NEAREST and tag_sets and tagging the secondaries.
Then if the secondaries have been tagged
{'secondaries': 1}
you can read from the nearest secondary like so:Update:
You should note that if an election occurs and the topology of your replicaset changes then you'd have to manually change the tag_sets to represent the new secondaries.
This answer is very specific to my situation, because my nearest secondary is in the same region as my web server (as good as running on the same machine), so the data transfer would be insanely fast, plus I don't have to pay for bandwidth usage (which over the month might become significant considering the amount of data).
Otherwise the default value for 'secondary_acceptable_latency_ms' = 15ms. So it doesn't really matter.
So in case someone finds himself/herself in the same situation, this is what to do:
Thanks!!