Search code examples
mongodbmongoenginereplicasetflask-mongoengine

How can I connect a mongodb replicaset using mongoengine?


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?


Solution

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