Today: April 21, 2021 4:28 pm
A collection of Software and Cloud patterns with a focus on the Enterprise

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.


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

options = new MongoOptions();
Mongo mongo = new Mongo(mongoNodesDBAddresses, options);


  1. […] 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

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.