Open In App

How to Read from Secondary Node in MongoDB ?

Last Updated : 28 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

MongoDB is a powerful NoSQL database that provides high availability and redundancy through replica sets. A replica set consists of multiple MongoDB nodes that maintain the same data set, ensuring fault tolerance and load balancing. By default, all read and write operations go to the primary node, but MongoDB allows read operations from secondary nodes to optimize performance and distribute load.

Understanding Replica Sets in MongoDB

A replica set in MongoDB consists of:

  • Primary Node: Handles all write operations by default.
  • Secondary Nodes: Maintain copies of the primary node’s data using oplog replication.
  • Arbiter (Optional): Does not store data but participates in elections to ensure a primary is always available.

Secondary nodes in a replica set can be used for read operations, backups, and disaster recovery.

Why Read from Secondary Nodes?

Reading from a secondary node has several benefits:

  • Load Balancing: Distributes read operations across multiple nodes, reducing the burden on the primary.
  • High Availability: Ensures applications can still read data if the primary node goes down.
  • Optimized Performance: Certain queries, such as reporting or analytics, can be executed on secondaries without impacting primary operations.

However, reading from secondaries comes with trade-offs:

  • Eventual Consistency: Secondary nodes might lag behind the primary due to replication delay.
  • Stale Reads: If a write operation has not yet been replicated, secondary reads might return outdated data.

How to Read from a Secondary Node in MongoDB

a) Using the Mongo Shell

To read from a secondary node in the MongoDB shell, you must set the read preference. Connect to your replica set and execute:

rs.slaveOk()

Alternatively, use the readPref option when querying:

db.collection.find().readPref("secondary")

b) Using MongoDB Drivers

MongoDB provides drivers for various programming languages. Below are examples of how to set read preferences using different drivers.

1. Node.js Driver

const { MongoClient } = require("mongodb");async function readFromSecondary() {
const uri = "mongodb://your_replica_set_uri/?readPreference=secondary";
const client = new MongoClient(uri);
try {
await client.connect();
const database = client.db("testDB");
const collection = database.collection("testCollection");

const docs = await collection.find({}).toArray();
console.log(docs);
} finally {
await client.close();
}
}readFromSecondary();

Explanation:

  • MongoClient(uri): Establishes a connection to the MongoDB replica set.
  • await client.connect(): Asynchronously connects to MongoDB.
  • database.collection("testCollection"): Selects the collection from which data will be read.
  • collection.find({}).toArray(): Executes a query to fetch all documents, returning them as an array.
  • The readPreference=secondary in the connection string ensures that reads are performed on a secondary node.

2. Python (PyMongo)

from pymongo import MongoClient, ReadPreferenceclient = MongoClient("mongodb://your_replica_set_uri")
db = client.get_database("testDB", read_preference=ReadPreference.SECONDARY)
collection = db["testCollection"]for doc in collection.find():
print(doc)3. Java Driverimport com.mongodb.client.*;
import com.mongodb.ReadPreference;public class ReadFromSecondary {
public static void main(String[] args) {
MongoClient mongoClient = MongoClients.create("mongodb://your_replica_set_uri");
MongoDatabase database = mongoClient.getDatabase("testDB").withReadPreference(ReadPreference.secondary());
MongoCollection<Document> collection = database.getCollection("testCollection"); for (Document doc : collection.find()) {
System.out.println(doc.toJson());
}
}
}

Explanation:

  • MongoClient("mongodb://your_replica_set_uri"): Connects to the MongoDB replica set.
  • get_database("testDB", read_preference=ReadPreference.SECONDARY): Sets the read preference to a secondary node.
  • collection.find(): Retrieves documents from the collection.
  • The loop prints each document fetched from the secondary node.

Setting Read Preferences in MongoDB Compass

MongoDB Compass, the official GUI for MongoDB, allows setting read preferences easily:

  • Open MongoDB Compass.
  • Connect to your replica set.
  • Click on Edit Read Preference.
  • Choose Secondary or Secondary Preferred.
  • Execute queries and observe data retrieved from secondary nodes.

Monitoring Read Operations on Secondary Nodes

To verify whether read operations are hitting secondary nodes, use the rs.status() command in the shell:

rs.status()

You can also check the MongoDB logs for read operations on secondary nodes.

Best Practices for Reading from Secondary Nodes

  • Use secondaryPreferred for High Availability: Ensures queries still run even if the primary is unavailable.
  • Monitor Replication Lag: Use rs.printSlaveReplicationInfo() to check if secondary nodes are lagging.
  • Avoid Critical Reads on Secondary Nodes: Since secondary nodes might be outdated, avoid using them for real-time transactions.
  • Configure Read Concerns: Use local, majority, or linearizable read concerns to balance consistency and availability.
  • Test Performance: Benchmark query performance when reading from secondaries vs. the primary.

Conclusion

Reading from secondary nodes in MongoDB is a useful feature for load balancing, high availability, and scalability. By leveraging read preferences, developers can optimize their database queries based on application needs. However, it’s essential to understand the trade-offs, particularly eventual consistency and replication lag.

By following best practices and monitoring secondary node performance, organizations can maximize the benefits of MongoDB’s replica sets while ensuring efficient database operations.


Next Article
Article Tags :

Similar Reads