Production MongoDB always runs as a replica set, and its durability depends on the concerns you choose.
A replica set is a group of mongod servers holding the same data, typically three. One is the primary and accepts all writes; the secondaries copy its changes by tailing the oplog, a capped collection of idempotent operations. If the primary becomes unreachable, the members hold an election and a secondary with the latest data becomes primary, usually within about ten seconds. Drivers discover the topology and reroute automatically; retryable writes (on by default) retry once after a failover.
Write concern says when a write is acknowledged: w: 1 after the primary applies it, w: "majority" after a majority of voting members have it (the default since 5.0). Only majority-acknowledged writes are guaranteed to survive a failover; a w: 1 write can be rolled back if the old primary dies before replicating it. j: true additionally waits for the journal.
Read preference chooses which member serves reads: primary (default), primaryPreferred, secondary, secondaryPreferred, nearest. Secondaries can lag, so reads from them may be stale.
Read concern says what data a read may return: "local" (default, may later be rolled back), "majority" (only majority-committed data), "snapshot" in transactions. Combine majority reads and writes with causal consistency sessions to read your own writes from secondaries.
Example
// three-member set, run once on one member
rs.initiate({ _id: "rs0", members: [
{ _id: 0, host: "db1:27017" }, { _id: 1, host: "db2:27017" }, { _id: 2, host: "db3:27017" } ] })
rs.status().members.map(m => m.stateStr) // [ 'PRIMARY', 'SECONDARY', 'SECONDARY' ]
// durable write: acknowledged once a majority has it, fail after 5 s
db.payments.insertOne({ amount: 50 }, { writeConcern: { w: "majority", wtimeout: 5000 } })
// analytics read from a secondary, accepting slight staleness
db.payments.find().readPref("secondaryPreferred")
// connection string form
// mongodb://db1,db2,db3/?replicaSet=rs0&w=majority&readPreference=primaryPreferredRemember
- One primary takes writes; secondaries replicate via the oplog
- Elections pick a new primary automatically on failure
- w: "majority" (default) writes survive failover; w: 1 writes can roll back
- Read preference picks the member; read concern picks the durability of data read
Watch out for
- Reading from secondaries for read-after-write flows and showing users stale data.
- Running two data-bearing members only: losing one leaves no majority to elect a primary.