Replication in MongoDB — MongoDB Technical Interview Questions & Answers
Replica sets for high availability and failover.
Replication in MongoDB
- Simple meaning: A replica set is several MongoDB servers holding the same data. One primary takes writes. Secondaries copy it.
- Why: if the primary dies, the set elects a new primary. Your app can keep reading (and later writing).
- How to use: Atlas already runs a replica set for you. Locally, rs.initiate() is for labs, not required for first CRUD.
- Try this (idea): db.hello() or rs.status() on a replica set to see who is primary.
- Common mistake: calling a replica set “sharding”. Replica = copies. Shard = split data.
- Interview tip: Primary writes, secondaries replicate, automatic failover. Atlas uses this by default.
Technical Interview Tip: Replica set = copies + failover. Not splitting data.
Code Examples for Replication in MongoDB
Replication in MongoDB — working example
// Replica set: primary takes writes; secondaries replicate.
rs.status()
// Sharding: data partitioned by shard key across shards
sh.status()
sh.shardCollection("prep_pilot.orders", { customerId: "hashed" })
db.orders.find({ customerId: 42 })Replication in MongoDB — replica sets give HA; sharding scales writes/data horizontally via a shard key.
How to Explain Replication in MongoDB to an Interviewer
What is a replica set?
Copies of the same data Primary + secondaries + election