I'm trying to connect to a MongoDB replicaSet using MongoEngine? I would like to connect to any available secondary server.
I can only find pyMongo examples. Any help?
If you want to connect to a secondary server you need to specify a read preference such as SECONDARY
or SECONDARY_PREFERRED
. Note that when reading data from a secondary you should anticipate the data is eventually consistent and may be stale (i.e. changes may not have replicated from the primary yet).
You will want to import ReadPreference
from the base pymongo
driver for a list of constants. You can specify a default read_preference
at the connection level, or per query.
Example using secondary preferred (will read from primary if secondary is not available):
from mongoengine import connect
from pymongo import ReadPreference
connect('mydb', host='mongodb://server1:27017,server2:27017,server3:27017', replicaSet='replset', read_preference=ReadPreference.SECONDARY_PREFERRED)
You can check if reads are going to secondaries using mongostat --discover
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With