Photo by Yosuke Ota on Unsplash

On this page

This chapter follows Geospatial queries in MongoDB. Production Atlas clusters run as replica sets by default. Self-hosted deployments should too unless you are doing a single-node local experiment.

Why replica sets exist

A replica set is a group of mongod processes that share the same data set. One member is primary and receives all writes; secondaries replicate the primary’s oplog and can serve reads depending on read preference. If the primary fails, members elect a new primary automatically.

Elections and roles

Each member has a priority (default 1). Higher priority members are preferred in elections. Check status in mongosh on the primary:

rs.status()
rs.isMaster().primary

To influence future elections (connect to the current primary):

const cfg = rs.conf()
cfg.members[0].priority = 3
cfg.members[1].priority = 2
cfg.members[2].priority = 1
rs.reconfig(cfg)

Local three-node set with Docker Compose

A minimal compose file for learning (not production hardening):

docker-compose.replicaset.yml
services:
mongo1:
image: mongodb/mongodb-community-server:8.0-ubuntu2204
command: ["--replSet", "rs0", "--bind_ip_all"]
ports: ["27017:27017"]
mongo2:
image: mongodb/mongodb-community-server:8.0-ubuntu2204
command: ["--replSet", "rs0", "--bind_ip_all"]
ports: ["27018:27017"]
mongo3:
image: mongodb/mongodb-community-server:8.0-ubuntu2204
command: ["--replSet", "rs0", "--bind_ip_all"]
ports: ["27019:27017"]

Initiate once:

rs.initiate({
_id: 'rs0',
members: [
{ _id: 0, host: 'localhost:27017' },
{ _id: 1, host: 'localhost:27018' },
{ _id: 2, host: 'localhost:27019' },
],
})

Read preference and write concern

From the driver:

const col = db.collection('events', {
readPreference: 'secondaryPreferred',
writeConcern: { w: 'majority', j: true },
});
Setting Meaning
primary Read from primary only (default)
secondaryPreferred Use secondary when healthy
w: 'majority' Acknowledged after majority of voting members
j: true Wait for journal flush

Stale reads are possible on secondaries; use primary for read-your-writes consistency.

Connection strings

Include the replica set name and multiple hosts:

Terminal window
mongodb://localhost:27017,localhost:27018,localhost:27019/myapp?replicaSet=rs0

Atlas mongodb+srv URIs include replica set parameters automatically.

Next: Transactions in MongoDB.

Search articles

Type a word to search published articles.

Open the search page