How to prefer reads on secondaries in MongoDb

Paul Gregoire picture Paul Gregoire · Jan 29, 2013 · Viewed 12k times · Source

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();

Answer

Paul Gregoire picture Paul Gregoire · Jan 31, 2013

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);