MongoDB ReadPreference

MongoDB connections accommodate a ReadPreference, which in a clustered environment, like a replicaset, indicates how to select the best host for a query. One major consideration when setting the read preference is whether or not you can live with eventually consistent reads, since SECONDARY hosts may lag behind the PRIMARY.

Some of the options you can choose include:

  • PRIMARY: This will ensure the most consistency, but also concentrates all your queries on a single host.
  • SECONDARY: This will distribute your queries among secondary nodes and may lag in consistency with the primary
  • primaryPreferred: Reads from the primary whenever it is available, but will fail over to secondary if necessary.
  • secondaryPreferred: Reads from the secondary whenever it is available, but will fail over to primary if necessary.
  • nearest: Reads from the nearest node as determined by the lowest latency between the client and node.

Here’s a great StackOverflow discussion about ReadPreference.

Integration

Setting the ReadPreference requires use of a MongoOptions object. That can then be used to create the Mongo object.

options = new MongoOptions();
options.setReadPreference(ReadPreference.nearest());
Mongo mongo = new Mongo(mongoNodesDBAddresses, options);
Twitter Digg Delicious Stumbleupon Technorati Facebook Email

About Daniel Watrous

I'm a Software & Electrical Engineer and online entrepreneur.

Trackbacks/Pingbacks

  1. MongoDB monitoring with mongotop | Daniel Watrous on Software Engineering - January 11, 2013

    […] running the experiment I set the ReadPreference to nearest. As a restult I expected to see a well balanced, but asymmetrical distribution between […]

Leave a Reply