Intermediate LevelMongoDB & Mongoose
What are MongoDB Read Preferences (primary, secondaryPreferred, nearest)?
❓ Interview Prompt: Explain Read Preferences (primary, primaryPreferred, secondary, secondaryPreferred, nearest), offloading read traffic, and eventual consistency.
Read Preference dictates which members of a Replica Set receive read query requests from client drivers:
•
'primary' (Default): Strictly reads from Primary node (guarantees strong consistency).
•
'secondaryPreferred': Reads from Secondaries to offload query traffic; falls back to Primary if Secondaries are offline.
•
'nearest': Reads from member with lowest network ping latency.
Code Implementation Example
typescript
import { AnalyticsModel } from './models/Analytics';
async function getAnalyticalReport() {
// Offload heavy analytical query to Secondary replica nodes!
const report = await AnalyticsModel.find()
.read('secondaryPreferred')
.exec();
return report;
}💡Routing read-heavy analytical queries to Secondary nodes via readPreference.
🎯 Interview Key Takeaway
Use secondaryPreferred read preference for heavy analytical queries to offload Primary node CPU while accepting eventual consistency.
#Read Preference#secondaryPreferred#Read Scaling#Intermediate
Back to all MongoDB & Mongoose Questions→