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
How MongoDB sort by relevance in Node.js ?
MongoDB is a popular, open-source NoSQL database that uses a document-oriented data model. It is designed to handle large amounts of data with high performance and scalability and is often used in big data and real-time web applications. In MongoDB, data is stored in BSON (binary JSON) format, which
4 min read
How to Make a Synchronous MongoDB Query in NodeJS?
MongoDB is a popular NoSQL database that is often used in modern web development. It is known for its flexibility, scalability, and ease of use. Node.js, with its non-blocking, event-driven architecture, is a natural fit for MongoDB. However, working with asynchronous code can sometimes be challengi
2 min read
How to use MongoDB Projection in Mongoose?
MongoDB projection in Mongoose allows you to specify which fields to include or exclude in query results, optimizing data retrieval by returning only the necessary information from the database.Prerequisites:Nodejs NPMMongoDBJavaScriptThere are several ways to specify projection in Mongoose:Table of
4 min read
How to Deploy a Replica Set in MongoDB?
MongoDB replica sets are crucial for ensuring high availability, fault tolerance, and data redundancy in MongoDB deployments. A replica set is a group of MongoDB instances that maintain the same dataset, offering a reliable solution for production environments.In this article, we will explain the pr
5 min read
How to Retrieve Data from MongoDB Using NodeJS?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for the storage and retrieval of data. Thi
3 min read
How to Use MongoDB Transactions in Node.js?
Using MongoDB transactions in Node.js involves several steps. Transactions allow multiple operations on the database to be executed in an all-or-nothing manner, ensuring data consistency. we will learn how to use MongoDB transaction in Node.js.PrerequisitesMongoDB (Version 4.0 or higher Recommended)
2 min read
How to replace one document in MongoDB using Node.js ?
MongoDB, the most popular NoSQL database, we can count the number of documents in MongoDB Collection using the MongoDB collection.countDocuments() function. The mongodb module is used for connecting the MongoDB database as well as used for manipulating the collections and databases in MongoDB. Inst
1 min read
How to Search by id in MongoDB
In MongoDB, each document in a collection is uniquely identified by a field called "_id". This "_id" field serves as the primary key and provides a unique identifier for each document. Searching by ID is a common operation in MongoDB and allows us to retrieve specific documents based on their unique
4 min read
How to Perform a findOne Operation in MongoDB using Node.js?
The findOne operation in MongoDB is used to get a single document from the collection if the given query matches the collection record. While using findOne, if more than one record is there with the exact same match, then it will return the very first one. We will use this operation if we need to fe
4 min read
How To Query For Documents In MongoDB Using NodeJS?
MongoDB is the popular NoSQL database that allows for flexible and scalable data storage. NodeJS and JavaScript runtime built on Chrome's V8 JavaScript engine. It is often used with MongoDB to build powerful and efficient applications. In this article, we will guide you on how to query the documents
4 min read