How to Read from Secondary Node in MongoDB ?
Last Updated :
28 Feb, 2025
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.
Similar Reads
SQL Interview Questions Are you preparing for a SQL interview? SQL is a standard database language used for accessing and manipulating data in databases. It stands for Structured Query Language and was developed by IBM in the 1970's, SQL allows us to create, read, update, and delete data with simple yet effective commands.
15+ min read
SQL Tutorial SQL is a Structured query language used to access and manipulate data in databases. SQL stands for Structured Query Language. We can create, update, delete, and retrieve data in databases like MySQL, Oracle, PostgreSQL, etc. Overall, SQL is a query language that communicates with databases.In this S
11 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
SQL Joins (Inner, Left, Right and Full Join) SQL joins are fundamental tools for combining data from multiple tables in relational databases. Joins allow efficient data retrieval, which is essential for generating meaningful observations and solving complex business queries. Understanding SQL join types, such as INNER JOIN, LEFT JOIN, RIGHT JO
6 min read
Normal Forms in DBMS In the world of database management, Normal Forms are important for ensuring that data is structured logically, reducing redundancy, and maintaining data integrity. When working with databases, especially relational databases, it is critical to follow normalization techniques that help to eliminate
7 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
ACID Properties in DBMS In the world of DBMS, transactions are fundamental operations that allow us to modify and retrieve data. However, to ensure the integrity of a database, it is important that these transactions are executed in a way that maintains consistency, correctness, and reliability. This is where the ACID prop
8 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read