How to prefer reads on secondaries in MongoDb

12,409

Solution 1

The correct answer, after much blood and sweat is as follows:

  • To prefer all reads / queries hit the secondaries, only slaveOk() need be set
  • To prefer only selected reads use secondaries, do not set slaveOk() and use queryNonPrimary() instead per query

It is also a good practice to set an appropriate write concern when using replica sets, like so:

mongo.setWriteConcern(WriteConcern.REPLICAS_SAFE);

Solution 2

It seems that the current method (as per Java driver 2.8+) is to do

MongoOptions options = new MongoOptions();
options.setReadPreference(ReadPreference.secondaryPreferred());

then

mongo = new com.mongodb.Mongo(Arrays.asList(address1, address2), options);

This will make all connections prefer using secondaries, but will use the primary as a backup if the secondary is down or unavailable for some reason.

Solution 3

Use the "SECONDARY" read preference http://www.mongodb.org/display/DOCS/Read+Preferences+and+Tagging+in+The+Java+Driver

"SECONDARY : Read from a secondary node if available, otherwise error."

Share:
12,409
Paul Gregoire
Author by

Paul Gregoire

I am a Java geek and all around technology nerd. I am here to help you and seek answers for myself. Since there has been some confusion in the past, I'd like to inform you all that my name is not Mondain, it is a handle that I've used since the mid 1980's. I am a core developer on the Red5 project. For Red5 help you can post here on stackoverflow with the red5 tag or subscribe to the users list ( http://groups.google.com/group/red5interest ). Github https://github.com/mondain LinkedIn http://www.linkedin.com/in/paulgregoire/ Don't get discouraged if your question is closed or you meet with resistance. There is a lot of value on these StackExchange sites and an ounce of research or due-diligence goes a long way with these folks.

Updated on June 21, 2022

Comments

  • Paul Gregoire
    Paul Gregoire almost 2 years

    When using mongodb in a replica set configuration (1 arbiter, 1 primary, 2 slaves); how do I set a preference that read be performed against the secondaries and leave the primary only for writes? I'm using MongoDb 2.0.4 with Morphia. I see that there is a slaveOk() method, but I'm not sure how that works.

    Morphia http://code.google.com/p/morphia/

    Details My Mongo is set with the following options:

    mongo.slaveOk();
    mongo.setWriteConcern(WriteConcern.SAFE);
    

    I am attempting to use the following (this may be answer -btw):

    Datastore ds = getDatastore();
    Query<MyEntity> query = ds.find(MyEntity.class).field("entityId").equal(entityId);
    query.queryNonPrimary(); // appears equivalent to ReadPrefererence.secondary()
    MyEntity entity = query.get();