0
0
MongoDBquery~5 mins

Read preference for replica sets in MongoDB

Choose your learning style9 modes available
Introduction

Read preference tells MongoDB where to get data from in a group of servers. It helps balance speed and data freshness.

When you want to read data from the main server only to get the latest updates.
When you want to read data from backup servers to reduce load on the main server.
When you want to read from the nearest server to get faster responses.
When you want to allow reading from any available server to maximize availability.
When you want to control how fresh the data should be when reading from backups.
Syntax
MongoDB
db.collection.find().readPref('mode')

// or when connecting:
MongoClient(uri, { readPreference: 'mode' })

'mode' can be primary, secondary, primaryPreferred, secondaryPreferred, or nearest.

Read preference can be set per query or for the whole connection.

Examples
Reads only from the primary server to get the most up-to-date data.
MongoDB
db.orders.find().readPref('primary')
Reads only from secondary servers to reduce load on the primary.
MongoDB
db.orders.find().readPref('secondary')
Reads from the closest server, primary or secondary, for faster response.
MongoDB
db.orders.find().readPref('nearest')
Sample Program

This example shows how to read from primary and secondary servers in a replica set.

MongoDB
use shop

// Read from primary
printjson(db.products.find().readPref('primary').limit(2).toArray())

// Read from secondary
printjson(db.products.find().readPref('secondary').limit(2).toArray())
OutputSuccess
Important Notes

Reading from secondaries may return slightly older data because of replication delay.

Use 'primaryPreferred' or 'secondaryPreferred' to allow fallback if preferred servers are unavailable.

Setting read preference helps distribute read load and improve performance.

Summary

Read preference controls which replica set member to read from.

It helps balance between data freshness and read performance.

You can set it per query or for the whole connection.