1.Replica sets
A replica set is a group of MongoDB servers holding the same data, so the loss of any one of them does not mean data loss or downtime. One member is the primary and accepts writes; the others are secondaries that continuously copy the primary's changes.
Key features
- A production replica set typically has an odd number of voting members (3, 5, 7) — odd counts avoid ties in an election
- Exactly one member is primary at a time; all writes go to it
- Secondaries continuously replicate the primary's oplog and apply the same changes
- If the primary becomes unreachable, the remaining members elect a new primary automatically, without operator intervention
- This is MongoDB's baseline high-availability building block — running production MongoDB as a lone standalone server is specifically what a replica set exists to avoid
- Application — sends writes
- leads to Primary (writes)
- Primary — accepts all writes
- leads to Secondary (oplog)
- leads to Secondary (oplog)
- Secondary — replicates from primary
- Secondary — replicates from primary
Command
rs.initiate({ _id: "rs0", members: [{ _id: 0, host: "m1" }, { _id: 1, host: "m2" }, { _id: 2, host: "m3" }] })A replica set is several servers holding the same data, one primary accepting writes at a time, with automatic election of a new primary if the current one becomes unreachable — this is MongoDB's baseline answer to "what happens when one server dies".