MongoDB Replica Set - Step by Step With Example

Author
April 10, 2022

In this article i will explain you step by step to create replica set in mongodb 5.0 community edition. A replica set in MongoDB is a group of mongod processes that maintain the same data set. Replica sets provide redundancy and high availability, and are the basis for all production deployments

Step 1: Create mongodb directories for mongodb instances

We will create three mongodb instances for that we will create three directories db1, db2, db3 inside one main parent directories named replica, you can choose any location in your computer to create these directories

replicaset-folders

Step 2: Create mongodb instances with replica set

We will create mongodb instances with replica set flag —replSet “Replica set name” you can keep any name for the replica set also you can choose any port you want here i will keep the port name as 27017, 27018, 27019

Creating first mongodb instance on default port that is 27017 replace the folder path with your folder path for db1

mongod --dbpath `your folder path for db1` --replSet myReplica

initiate-replicaset

Creating second mongodb instance on port 27018 replace the folder path with your folder path for db2

mongod --dbpath `your folder path for db2` --replSet myReplica --port 27018

Creating third mongodb instance on port 27019 replace the folder path with your folder path for db3

mongod --dbpath `your folder path for db3` --replSet myReplica --port 27019

Step 3: Configuring and initiating replica set

It’s time to configure replica set myReplica

var configuration = {
  _id: "myReplica",
  members: [
    { _id: 0, host: "localhost:27017" },
    { _id: 1, host: "localhost:27018", secondaryDelaySecs: 20, priority: 0 },
    { _id: 2, host: "localhost:27019" },
  ],
};

Connect to one of the mongo instance that is on port 27017 and initiate the replica set

mongo --port 27017

connect-mongo-instance

rs.initiate(configuration);

replica-set-initiate

Step 4: Reading and writing data replica set

After following above steps you will be able to successfully create replica set server with one primary and two secondary. We can read and write data to our primary server but can only read from our secondary server

Our primary server is port so we connect to primary server mongo —port 27017 and inserts some data

use replica
db.people.insert({name:'Anku'});
show collections
db.people.find({}).pretty()

insert-data-replica-set

In order to read from secondary server we need to run command rs.secondaryOk(true) first then read data, iam connected to server on port 27018

rs.secondaryOk(true);
show dbs
use replica
show collections
db.people.find({}).pretty()

read-data-replica-set

Step 5: Watch our you tube video to follow the above steps