Skip to content
MongoDB

Replica Set

Configure a replica set for high availability.

By EZ4Code Team
replicationreplica-setha

Code

// Initiate a replica set
rs.initiate({
  _id: "rs0",
  members: [
    { _id: 0, host: "mongo1:27017" },
    { _id: 1, host: "mongo2:27017" },
    { _id: 2, host: "mongo3:27017" }
  ]
});

// Inspect and manage
rs.status()
rs.conf()
rs.add("mongo4:27017")
rs.remove("mongo4:27017")
rs.stepDown(60)        // force primary to step down

// Read preference on the client
// mongodb://host1,host2,host3/db?replicaSet=rs0&readPreference=secondaryPreferred

Explanation

A replica set synchronizes data across multiple members for redundancy and automatic failover. One member is primary and accepts writes; the rest are secondaries replicating the oplog. readPreference=secondaryPreferred lets reads hit secondaries to offload the primary, at the cost of read staleness.

More MongoDB Snippets