Read Preferences
Read Preferences: free step-by-step lesson with examples, common mistakes, and interview tips — part of MongoDB Tutorial on Toolliyo Academy.
On this page
MongoDB Tutorial · Lesson 64 of 100
Read Preferences
Foundations & CRUD ✓ → Queries & Schema ✓ → Aggregation & Scale → Atlas & Projects
Aggregation & Scale · 3 — Pipelines · ~10 min · MongoDB — Replication & Sharding
What is this?
Read preference controls which replica set member serves reads: primary, primaryPreferred, secondary, secondaryPreferred, or nearest. Write concern is separate — writes still go to the primary.
Why should you care?
Heavy analytics can read from secondaries so the primary keeps serving checkout writes.
See it live — copy this example
Open mongosh or MongoDB Compass, select database nosqlverse, then run the example. Change one field and run again.
// mongosh
db.getMongo().setReadPref("secondaryPreferred")
db.orders.find({ tenantId: "acme" }).limit(5)
// Node driver URI option: ?readPreference=secondaryPreferred
// or collection.find(q).withReadPreference(ReadPreference.secondary)
Run Example »
Edit the code below and click Run to see the result in Toolliyo’s live editor.
What happened?
- secondaryPreferred tries a secondary, falling back to primary if needed.
- Stale reads are possible because replication lags.
- Do not use secondary reads for read-your-writes checkout confirmation without care.
Practice next
- Set read pref secondaryPreferred in mongosh on a replica set.
- Run a find and check which host served it if possible.
- List which APIs can tolerate lag.
- Try nearest for multi-region apps.
- Combine with maxStalenessSeconds in drivers.
Remember
Read preference chooses read targets. Secondaries may be slightly stale. Use for analytics and heavy reads.
Report reads vs checkout writes
Seller reports use secondaryPreferred; place-order uses primary.
Outcome: Dashboards scale out without starving purchases.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!