MongoDB - Replication
Replication in MongoDB is the process of synchronizing data across multiple servers. It provides redundancy, increases data availability, and allows for disaster recovery and high availability of data.
Why Replication?β
- Data Safety: Keeps your data safe with multiple copies.
- High Availability: Ensures 24/7 availability of data.
- Disaster Recovery: Helps in recovering from disasters.
- No Downtime: No downtime for maintenance activities.
- Read Scaling: Provides extra copies for reading operations.
- Transparent to Application: Replica set is transparent to applications.
How Replication Works in MongoDBβ
MongoDB achieves replication through the use of a replica set, which is a group of mongod instances hosting the same data set. Here's how it works:
Replica Set Featuresβ
- Cluster of N nodes.
- Any one node can be primary.
- All write operations go to the primary.
- Automatic failover and recovery.
- Consensus election of primary.
Set Up a Replica Setβ
To set up a replica set, follow these steps:
-
Shutdown the running MongoDB server.
-
Start the MongoDB server with the
--replSet
option:mongod --port "PORT" --dbpath "YOUR_DB_DATA_PATH" --replSet "REPLICA_SET_INSTANCE_NAME"
Example:
mongod --port 27017 --dbpath "D:\set up\mongodb\data" --replSet rs0
-
Connect to this mongod instance and issue the command
rs.initiate()
to initiate a new replica set. -
Use
rs.conf()
to check the replica set configuration andrs.status()
to check the status of the replica set.
Add Members to Replica Setβ
To add members to a replica set:
- Start mongod instances on multiple machines.
- Connect to the primary node in the Mongo client.
- Issue the
rs.add()
command to add members to the replica set.
Syntaxβ
>rs.add(HOST_NAME:PORT)
Example:
>rs.add("mongod1.net:27017")
NOTE : You can add mongod instances to the replica set only when connected to the primary node. Use
db.isMaster()
to check your connection status.