Bird
Raised Fist0
MongoDBquery~10 mins

Read preference for replica sets in MongoDB - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Read preference for replica sets
Client issues read request
↓
Check read preference setting
↓
Primary
↓
Send read to chosen replica
↓
Receive data from replica
↓
Return data to client
The client decides which replica to read from based on the read preference, then sends the read request to that replica and returns the data.
Execution Sample
MongoDB
db.collection.find().readPref('secondary')
This query reads data from a secondary replica in the replica set.
Execution Table
StepRead PreferenceReplica ChosenActionResult
1secondarySecondary replicaSend read requestRead data from secondary
2primaryPrimary replicaSend read requestRead data from primary
3primaryPreferredPrimary replica if availableSend read requestRead data from primary
4primaryPreferredSecondary replica if primary downSend read requestRead data from secondary
5secondaryPreferredSecondary replica if availableSend read requestRead data from secondary
6secondaryPreferredPrimary replica if no secondarySend read requestRead data from primary
7nearestReplica with lowest latencySend read requestRead data from nearest replica
8---Stop: Read completed and data returned
💡 Read completes after sending request to chosen replica and receiving data
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
readPreferencenot setsecondaryprimaryprimaryPreferredsecondaryPreferrednearest
replicaChosennonesecondaryprimaryprimarysecondarynearest
readResultnonedata from secondarydata from primarydata from primary or secondarydata from secondary or primarydata from nearest replica
Key Moments - 3 Insights
Why does 'primaryPreferred' sometimes read from secondary?
Because if the primary is down or unreachable, 'primaryPreferred' falls back to reading from a secondary, as shown in execution_table rows 3 and 4.
What happens if no secondary is available but read preference is 'secondaryPreferred'?
The read goes to the primary replica instead, as shown in execution_table row 6.
How does 'nearest' read preference decide which replica to read from?
'Nearest' chooses the replica with the lowest network latency, regardless of primary or secondary status, as shown in execution_table row 7.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, which replica does 'secondaryPreferred' read from if a secondary is available?
APrimary replica
BSecondary replica
CNearest replica
DNo replica
💡 Hint
Check execution_table row 5 under 'Replica Chosen'
At which step does the read preference fall back to secondary if primary is down?
AStep 2
BStep 3
CStep 4
DStep 6
💡 Hint
Look at execution_table rows 3 and 4 for 'primaryPreferred' behavior
If the read preference is 'nearest', which replica is chosen?
AReplica with lowest latency
BSecondary replica only
CPrimary replica only
DRandom replica
💡 Hint
See execution_table row 7 for 'nearest' read preference
Concept Snapshot
Read preference controls which replica in a MongoDB replica set handles read queries.
Options include primary, secondary, primaryPreferred, secondaryPreferred, and nearest.
The client sends reads to the chosen replica based on preference and availability.
Fallbacks occur if preferred replicas are unavailable.
This helps balance load and improve read scalability.
Full Transcript
This visual execution trace shows how MongoDB clients decide which replica to read from in a replica set based on the read preference setting. The client first checks the read preference, then selects the appropriate replica: primary, secondary, or nearest. For example, 'secondaryPreferred' reads from a secondary if available, otherwise falls back to primary. The execution table steps through each preference and the replica chosen, showing the read request sent and data returned. Variable tracking shows how the readPreference and replicaChosen change at each step. Key moments clarify common confusions like fallback behavior. The quiz tests understanding of which replica is chosen under different preferences. The snapshot summarizes the concept simply for quick review.

Practice

(1/5)
1. What does the readPreference setting control in a MongoDB replica set?
easy
A. The size of the replica set
B. Which member to write data to
C. How often data is backed up
D. Which replica set member to read data from

Solution

  1. Step 1: Understand the role of readPreference

    The readPreference setting tells MongoDB which replica set member to use for read operations.
  2. Step 2: Differentiate read and write roles

    Writes always go to the primary, but reads can be directed to primary or secondary members based on readPreference.
  3. Final Answer:

    Which replica set member to read data from -> Option D
  4. Quick Check:

    Read preference = controls read source [OK]
Hint: Read preference decides read source, not write or backup [OK]
Common Mistakes:
  • Confusing readPreference with write concern
  • Thinking it controls backups
  • Assuming it changes replica set size
2. Which of the following is the correct syntax to set read preference to secondaryPreferred in a MongoDB connection string?
easy
A. mongodb://host1,host2/?readPreference=secondaryPreferred
B. mongodb://host1,host2/?readPreference=primaryOnly
C. mongodb://host1,host2/?readPref=secondaryPreferred
D. mongodb://host1,host2/?readPreference=secondaryOnly

Solution

  1. Step 1: Identify correct parameter name

    The correct parameter to set read preference in the connection string is readPreference.
  2. Step 2: Match correct value

    secondaryPreferred is a valid read preference mode; others like primaryOnly or secondaryOnly are invalid or incorrect.
  3. Final Answer:

    mongodb://host1,host2/?readPreference=secondaryPreferred -> Option A
  4. Quick Check:

    Use readPreference with valid mode [OK]
Hint: Use exact parameter name 'readPreference' and valid mode [OK]
Common Mistakes:
  • Using 'readPref' instead of 'readPreference'
  • Using invalid modes like 'primaryOnly'
  • Misspelling 'secondaryPreferred'
3. Given the following MongoDB query with read preference set to secondary:
db.collection.find({ status: "active" }).readPref("secondary")
What will happen if all secondary members are down?
medium
A. The query will read from the primary member
B. The query will fail with an error
C. The query will wait until a secondary is available
D. The query will return empty results

Solution

  1. Step 1: Understand 'secondary' read preference behavior

    When read preference is set to secondary, reads must come from secondary members only.
  2. Step 2: Consider all secondaries down scenario

    If no secondary is available, the query cannot read from primary or fallback; it results in an error.
  3. Final Answer:

    The query will fail with an error -> Option B
  4. Quick Check:

    Strict 'secondary' fails if no secondary [OK]
Hint: Strict 'secondary' read fails if no secondary available [OK]
Common Mistakes:
  • Assuming fallback to primary happens automatically
  • Thinking query waits indefinitely
  • Expecting empty results instead of error
4. You wrote this code to read from a secondary member:
db.collection.find().readPref('secondaryPreferred')
But it still reads from the primary. What is the likely cause?
medium
A. The query must specify a filter to use read preference
B. The syntax for setting read preference is incorrect
C. No secondary members are available, so it falls back to primary
D. Read preference only works for writes

Solution

  1. Step 1: Understand 'secondaryPreferred' behavior

    This mode reads from secondary if available; otherwise, it falls back to primary.
  2. Step 2: Reason why primary is used

    If no secondary is available or reachable, the driver reads from primary as fallback.
  3. Final Answer:

    No secondary members are available, so it falls back to primary -> Option C
  4. Quick Check:

    'secondaryPreferred' falls back to primary if no secondary [OK]
Hint: 'secondaryPreferred' falls back to primary if no secondary [OK]
Common Mistakes:
  • Thinking syntax is wrong when it is correct
  • Believing read preference needs a filter
  • Confusing read preference with write behavior
5. You want to optimize read performance by reading from secondaries but ensure data is fresh enough. Which read preference mode should you choose?
hard
A. secondaryPreferred
B. nearest
C. primary
D. secondary

Solution

  1. Step 1: Understand read preference modes

    primary reads only from primary (fresh but may be slower), secondary reads only from secondaries (may be stale), secondaryPreferred reads secondaries or falls back to primary, nearest reads from the closest member regardless of type.
  2. Step 2: Balance freshness and performance

    secondaryPreferred prefers secondaries for read performance optimization but falls back to the primary to ensure data freshness and availability.
  3. Final Answer:

    secondaryPreferred -> Option A
  4. Quick Check:

    secondaryPreferred prefers secondary perf + primary freshness fallback [OK]
Hint: 'secondaryPreferred' for secondary perf with primary fallback [OK]
Common Mistakes:
  • Choosing 'secondary' which may return stale data
  • Choosing 'primary' which may be slower
  • Confusing 'secondaryPreferred' with 'nearest'
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard