Databases 17 min read

Mastering MongoDB Replica Sets: Setup, Configuration, and Read/Write Strategies

This guide explains MongoDB replica set fundamentals, walks through local deployment of a primary‑secondary‑secondary cluster, demonstrates automatic failover, and details write concern and read preference options—including member attributes, connection string parameters, and shell commands—for reliable high‑availability data handling.

Aotu Lab
Aotu Lab
Aotu Lab
Mastering MongoDB Replica Sets: Setup, Configuration, and Read/Write Strategies

MongoDB Replica Set Overview

Replica set consists of one primary and up to 50 secondary members. The primary handles all write operations, while secondaries replicate the primary's oplog. If the primary fails, eligible secondaries automatically hold an election to select a new primary. Member attributes include priority , hidden , slaveDelay , tags , and votes . Only seven members may vote in elections.

Replica set architecture diagram
Replica set architecture diagram

An arbiter (a voting node without data) can be added when only one secondary is available to maintain quorum.

Arbiter node diagram
Arbiter node diagram

Local P‑S‑S Replica Set Setup

Create three data directories and start three mongod instances on ports 27018, 27019, and 27020.

mkdir -p /data/mongodb/rs0-0 /data/mongodb/rs0-1 /data/mongodb/rs0-2

mongod --replSet rs0 --port 27018 --bind_ip localhost --dbpath /data/mongodb/rs0-0 --oplogSize 128
mongod --replSet rs0 --port 27019 --bind_ip localhost --dbpath /data/mongodb/rs0-1 --oplogSize 128
mongod --replSet rs0 --port 27020 --bind_ip localhost --dbpath /data/mongodb/rs0-2 --oplogSize 128

Initiate the replica set from the primary shell:

rsconf = {
    _id: "rs0",
    members: [
        { _id: 0, host: "localhost:27018" },
        { _id: 1, host: "localhost:27019" },
        { _id: 2, host: "localhost:27020" }
    ]
}
rs.initiate(rsconf)

Verify the configuration with rs.conf() and the current state with rs.status().

Automatic Failover Test

Terminate the primary (port 27018). The remaining members hold an election; logs show vote requests and a successful election. Use rs.status() to confirm the new primary (e.g., localhost:27019) and that the stopped node reports health: 0.

2020-10-26T21:43:58.156+0800 I  REPL ... VoteRequester(term 17) received a yes vote from localhost:27020 ...
2020-10-26T21:43:58.164+0800 I  ELECTION ... election succeeded, assuming primary role in term 17

Write Concern

Write concern defines how many members must acknowledge a write before the client receives success. Default {w:1} requires only the primary. {w:2} or {w:"majority"} requires acknowledgments from secondaries, protecting against data loss if the primary crashes.

db.products.insert(
    { item: "envelopes", qty: 100, type: "Clasp" },
    { writeConcern: { w: "majority", wtimeout: 5000 } }
)

To change the default for the replica set:

cfg = rs.conf()
cfg.settings.getLastErrorDefaults = { w: "majority", wtimeout: 5000 }
rs.reconfig(cfg)

Read Preference

Read operations can target the primary or secondaries. Five modes are available:

primary – all reads from the primary.

primaryPreferred – reads from primary if available; otherwise from a secondary.

secondary – all reads from secondaries.

secondaryPreferred – reads from secondaries unless none are available, then from primary.

nearest – reads from the node with the lowest network latency (primary or secondary).

Additional selectors refine node choice:

Tag sets – assign custom tags (e.g., region, datacenter) to members and query by those tags.

maxStalenessSeconds – maximum allowed replication lag; values below 90 seconds are rejected.

Hedged reads – in sharded clusters (MongoDB 4.4+), the driver sends the read to two suitable nodes and returns the fastest response.

Example connection string with read‑preference options:

mongodb://db0.example.com,db1.example.com,db2.example.com/?replicaSet=myRepl&readPreference=secondary&maxStalenessSeconds=120&readPreferenceTags=dc:ny,rack:r1

In the mongo shell, a query can specify a preference:

db.collection.find().readPref(
    "secondary",
    [ { "datacenter": "B" }, {} ],
    { enabled: true }
)

Read Preference Test

Connect to the primary ( mongo localhost:27018) and insert a document: db.nums.insert({name: "num0"}) Connect to a secondary ( mongo localhost:27019) and run a read. The default mode ( primary) returns NotMasterNoSlaveOk.

Specify the mode: db.nums.find().readPref("secondary") The document is returned, confirming the preference works.

Key Takeaways

Replica sets provide high availability through automatic failover and configurable member attributes.

A local development replica set can be created with three mongod processes and rs.initiate().

Write concern and read preference give fine‑grained control over durability and load distribution across the set.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

MongoDBFailoverDatabase ConfigurationRead PreferenceReplica SetWrite Concern
Aotu Lab
Written by

Aotu Lab

Aotu Lab, founded in October 2015, is a front-end engineering team serving multi-platform products. The articles in this public account are intended to share and discuss technology, reflecting only the personal views of Aotu Lab members and not the official stance of JD.com Technology.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.