0
0
MongoDBquery~5 mins

Read from secondaries trade-offs in MongoDB

Choose your learning style9 modes available
Introduction
Reading from secondary servers helps spread out the work and can make your app faster, but it might show data that is a little old.
When you want to reduce the load on the main database server.
When your app can handle slightly older data without problems.
When you want faster read responses by using nearby secondary servers.
When you need to keep your main server focused on writing data.
When you want to improve availability by reading from multiple servers.
Syntax
MongoDB
db.collection.find().readPref('secondary')
Use readPref('secondary') to tell MongoDB to read from secondary servers.
Secondary servers might not have the very latest data because of replication delay.
Examples
Reads user data from a secondary server to reduce load on the main server.
MongoDB
db.users.find().readPref('secondary')
Reads from secondary if available, otherwise reads from primary.
MongoDB
db.orders.find().readPref('secondaryPreferred')
Always reads from the primary server to get the most up-to-date data.
MongoDB
db.products.find().readPref('primary')
Sample Program
This query reads the list of products from a secondary server to avoid putting extra work on the primary server.
MongoDB
use shopDB
// Read product list from secondary to reduce load
const products = db.products.find().readPref('secondary').toArray()
printjson(products)
OutputSuccess
Important Notes
Secondary reads may return data that is slightly out of date due to replication lag.
If your application needs the latest data, always read from the primary server.
Using 'secondaryPreferred' is a good balance if you want to read from secondaries but fall back to primary if needed.
Summary
Reading from secondaries helps balance load and improve read speed.
Data from secondaries might be a bit old because of replication delay.
Choose read preference based on how fresh your data needs to be.