![]() |
VOOZH | about |
A MongoDB replica set is a group of nodes that maintain the same dataset to provide high availability, redundancy, and automatic failover for reliable read and write operations.
In a MongoDB replica set, all write operations go to the primary node, which records changes in its oplog and replicates them to secondary nodes asynchronously.
Example: Writing to the Primary Node
// Insert a document into the collection
db.myCollection.insertOne({ "name": "Alex", "age": 30 })
Output:
{
"acknowledged": true,
"insertedId": ObjectId("60f9d7ac345b7c9df348a86e")
}
Upon successful execution of the write operation, MongoDB returns an acknowledgment indicating that the operation was successful:
In a MongoDB replica set, reads go to the primary by default for strong consistency, but can be routed to secondary nodes using read preferences to improve scalability and availability.
Example: Read from Secondary Node
// Set read preference to read from secondary nodes
collection.find().readPreference("secondary")
Output:
{ "_id": ObjectId("60f9d7ac345b7c9df348a86e"), "name": "Alice", "age": 30 }When reading from a secondary node, MongoDB routes the read operation to one of the secondary nodes. The output will contain the queried data from the secondary node.
MongoDB provides different read preferences to balance performance and consistency:
| Read Preference | Description |
|---|---|
| primary (default) | Reads from the primary only. Ensures strong consistency. |
| primaryPreferred | Reads from the primary if available, otherwise falls back to a secondary. |
| secondary | Reads from secondary nodes for load balancing. May return stale data. |
| secondaryPreferred | Reads from secondaries but uses primary if no secondary is available. |
| nearest | Reads from the nearest node (primary or secondary) based on network latency. |
MongoDB provides additional options to control the behavior of read and write operations: