Daniel Watrous on Software Engineering

A Collection of Software Problems and Solutions

Software Engineering

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

1 Comment MongoDB ReadPreference

  1. Pingback: MongoDB monitoring with mongotop | Daniel Watrous on Software Engineering

Leave A Comment