liveBook · Manning

Read preference

As explained in MongoDB 8.0 in Action, Third Edition

Read preference is a MongoDB setting that determines whether read operations are directed to the primary or secondary members of a replica set.

Read preference determines which replica set members handle MongoDB read operations. The default primary mode returns the most up-to-date data, while secondary modes can distribute load and improve availability or performance at the cost of potentially stale results. section 9.5 section 9.5.3

Choose a mode according to the application's consistency, availability, and workload requirements:

  • primary routes every read to the primary and suits consistency-critical applications. section 9.5.3
  • primaryPreferred uses the primary when available and falls back to a secondary during primary downtime. section 9.5.3
  • secondary routes reads exclusively to secondary members, reducing primary load but potentially returning stale data. section 9.5.3
  • secondaryPreferred favors secondary members but falls back to the primary when no secondary is available. section 9.5.3
  • nearest selects the member with the lowest network latency, whether primary or secondary. section 9.6

Route a query to a preferred secondary

Use db.routes.find({ src_airport: 'MUC' }).readPref('secondaryPreferred') to favor secondary nodes while retaining primary fallback. section 9.5.3

mongodb+srv://<USERNAME>:<PASSWORD>@mongodb-in-
➥action.mongodb.net/test?readPreference=secondary&
➥readPreferenceTags=nodeType:ANALYTICS&
readConcernLevel=local

Connect exclusively to analytics nodes by combining secondary read preference with an analytics-node tag and a local read concern. section 10.5.1

How MongoDB 8.0 in Action, Third Edition covers it

How deep it goes
Defines five routing modes and their trade-offs, then applies secondary routing to analytics and operational workloads.
Examples
Uses a secondaryPreferred query and tagged connection strings for analytics and operational secondary nodes.
What it assumes
Assumes a MongoDB replica set and distinguishes read routing from read and write acknowledgment settings.
What you can do after
Operate/configure MongoDB clients to route reads toward primary, secondary, nearest, analytics, or operational nodes.
How it connects
Connects read preference with replica sets, read concern, write concern, read preference tags, analytics nodes, and reporting workloads.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of MongoDB 8.0 in Action, Third Edition. The section links point to the parts of the book it draws on.