What is a MongoDB replica set?

IntermediateConceptMongoDB
Answer

Short answer

A replica set is a group of mongod servers holding the same data: one primary receives all writes, and secondaries replicate from it. If the primary fails, the members elect a new primary automatically, usually within seconds. Production MongoDB always runs as a replica set (usually 3 members).

Picture

          writes
App ──▶  PRIMARY ── oplog ──▶ SECONDARY 1
                       └────▶ SECONDARY 2
(primary fails → secondaries vote → one becomes PRIMARY)

Why 3 members?

Elections need a majority. With 3 members, one can fail and the remaining 2 still form a majority. (An arbiter can vote without holding data, but data-bearing members are preferred.)

Commands

rs.initiate({ _id: "rs0", members: [
  { _id: 0, host: "mongo-0:27017" }, { _id: 1, host: "mongo-1:27017" }, { _id: 2, host: "mongo-2:27017" } ] })
rs.status()        // states: PRIMARY / SECONDARY, lag
rs.conf()
rs.stepDown()      // ask the primary to step down (maintenance)

Connection string

mongodb://app:pass@mongo-0:27017,mongo-1:27017,mongo-2:27017/shop?replicaSet=rs0

The driver discovers the primary and fails over automatically.

What to say in the interview

"A replica set is a primary plus secondaries replicating via the oplog, with automatic elections on failure. Three data-bearing members give majority voting with one failure tolerated, and apps use a replicaSet connection string so drivers follow the primary."

All Databases (MySQL, PostgreSQL, MongoDB) questions Roadmap: MongoDB basics

More on MongoDB