Read Preference in MongoDB: What It Is and How It Works
read preference controls which replica set members your queries read data from. It lets you choose to read from the primary, secondary, or other members to balance consistency and performance.How It Works
Imagine you have a library with multiple copies of the same book in different rooms. Read preference in MongoDB is like choosing which room to get your book from. You can pick the main room (primary) where all new books arrive, or a side room (secondary) that has copies but might be a little behind.
MongoDB uses replica sets to keep copies of data on multiple servers. The primary server handles all writes and has the freshest data. Secondary servers replicate data from the primary but might lag slightly. Read preference tells MongoDB where to send your read requests, balancing between getting the newest data and spreading the load to improve speed.
Example
This example shows how to set read preference to secondary in a MongoDB client using Node.js. This means reads will go to secondary members, reducing load on the primary.
const { MongoClient, ReadPreference } = require('mongodb'); async function run() { const uri = 'mongodb://localhost:27017,localhost:27018,localhost:27019/?replicaSet=rs0'; const client = new MongoClient(uri, { readPreference: ReadPreference.SECONDARY }); try { await client.connect(); const db = client.db('testdb'); const collection = db.collection('testcollection'); const doc = await collection.findOne({}); console.log('Read document:', doc); } finally { await client.close(); } } run().catch(console.dir);
When to Use
Use read preference to improve your app's performance or availability. For example, if you want the most up-to-date data, read from the primary. If you want to reduce load on the primary or can tolerate slightly stale data, read from secondary members.
In reporting or analytics, reading from secondaries can speed up queries without affecting writes. In disaster recovery, reading from secondaries in different locations can keep your app running if the primary is down.
Key Points
- Primary: Reads always from the main server with the freshest data.
- Secondary: Reads from copies that may lag behind.
- Nearest: Reads from the closest member based on network latency.
- Choosing read preference balances data freshness and performance.
- Use read preference settings in your MongoDB client configuration.