How can I connect a mongodb replicaset using mongoengine?
Asked Answered
I

1

9

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?

Ideation answered 18/12, 2013 at 20:6 Comment(0)
P
11

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.

Patrinapatriot answered 1/1, 2014 at 22:17 Comment(2)
This looks good, but how can I force the connection to use a secondary and avoid using the primary server? In the example above it will connect to the first one there is a change it is the primary server.Ideation
@rat: Sorry, missed the part about reading from secondary :). I've corrected the example.Patrinapatriot

© 2022 - 2025 — McMap. All rights reserved.