Problem Statement
What is a replica set in MongoDB?
Explanation
A replica set is a group of mongod instances that maintain the same data set. It consists of one primary node that receives all write operations and multiple secondary nodes that replicate the primary's data.
Replica sets provide redundancy and high availability. If the primary node fails, an automatic election process selects a new primary from the secondaries, ensuring continuous service. This is the foundation of MongoDB's fault tolerance and data durability.
Code Solution
SolutionRead Only
// Replica set configuration
rs.initiate({
_id: "myReplicaSet",
members: [
{ _id: 0, host: "mongodb0.example.net:27017" },
{ _id: 1, host: "mongodb1.example.net:27017" },
{ _id: 2, host: "mongodb2.example.net:27017" }
]
})
// Check replica set status
rs.status()