MongoDB Replication

Ensuring data availability and redundancy

🔄 What is MongoDB Replication?

Replication creates multiple copies of your data across different servers. It ensures high availability, data redundancy, and automatic failover if the primary server fails.


// Initialize a replica set
rs.initiate({
  _id: "myReplicaSet",
  members: [
    { _id: 0, host: "localhost:27017" }
  ]
})
                                    

Output:

{ "ok" : 1 }

Key Replication Concepts

👑

Primary Node

Receives all write operations

// Check replica set status
rs.status()
📋

Secondary Nodes

Replicate data from primary

// Add secondary member
rs.add("localhost:27018")
🔄

Automatic Failover

Elects new primary if needed

// View current primary
rs.isMaster()
📊

Oplog

Records all data operations

// View oplog
use local
db.oplog.rs.find()

🔹 Setting Up a Replica Set

Replica sets provide redundancy and high availability. Here's how to configure a basic three-member replica set for production use.

// Configure a 3-member replica set
rs.initiate({
  _id: "myReplicaSet",
  members: [
    { _id: 0, host: "mongodb0.example.net:27017" },
    { _id: 1, host: "mongodb1.example.net:27017" },
    { _id: 2, host: "mongodb2.example.net:27017" }
  ]
})

// Verify configuration
rs.conf()

Output:

{
  "_id" : "myReplicaSet",
  "version" : 1,
  "members" : [ ... ]
}

🔹 Adding Members to Replica Set

You can dynamically add or remove members from your replica set to scale your deployment.

// Add a new secondary member
rs.add("mongodb3.example.net:27017")

// Add an arbiter (voting member only)
rs.addArb("mongodb4.example.net:27017")

// Remove a member
rs.remove("mongodb3.example.net:27017")

Output:

{ "ok" : 1 }

🔹 Read Preferences

Control where your application reads data from in a replica set to optimize performance and data consistency.

// Read from primary only (default)
db.collection.find().readPref("primary")

// Read from secondary nodes
db.collection.find().readPref("secondary")

// Read from primary preferred
db.collection.find().readPref("primaryPreferred")

// Read from nearest node
db.collection.find().readPref("nearest")

🔹 Monitoring Replica Set Health

Regular monitoring ensures your replica set operates smoothly and helps identify issues early.

// Check replica set status
rs.status()

// View replication lag
rs.printReplicationInfo()

// Check secondary lag
rs.printSecondaryReplicationInfo()

// View current configuration
rs.conf()

Output:

configured oplog size: 1024MB
log length start to end: 3600secs
oplog first event time: Mon Jan 01 2024
oplog last event time: Mon Jan 01 2024

🧠 Test Your Knowledge

What is the minimum number of members recommended for a production replica set?