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?

rat
  • 1,277
  • 16
  • 24

1 Answers1

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.

warvariuc
  • 57,116
  • 41
  • 173
  • 227
Stennie
  • 63,885
  • 14
  • 149
  • 175
  • 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. – rat Jan 05 '14 at 02:13
  • @rat: Sorry, missed the part about reading from secondary :). I've corrected the example. – Stennie Jan 05 '14 at 03:50