How to Add Index on Secondary Replicaset in MongoDB

Connect with

MongoDB
Adding of index on primary in the replicaSet and that created index would replicate to Secondary node. But sometimes we required to create index on secondary only. The question is why we required on Secondary only, it’s basically for read optimize index as we read from Secondary.

Step 1. Start mongod Processes

open linux terminal and type following command to create 3 different directories for primary, secondary and arbital mongodb.

mkdir pri sec arb

Start mongod processes for primary, secondary and arbital on 3 different port by using following command.

mongod --replSet rs1--logpath "1.log" --dbpath pri --port 27017 --smallfiles --oplogSize 64 --fork 
mongod --replSet rs1 --logpath "2.log" --dbpath sec --port 27018 --smallfiles --oplogSize 64 --fork
mongod --replSet rs1 --logpath "3.log" --dbpath arb --port 27019 --smallfiles --oplogSize 64 --fork

Step 2. Config replicaSet

mongo --port 27017 < config.js
## On the mongo shell add an arbiter: 
rs.addArb("localhost:27019")

file config.js

config = { _id: "rs1", members:[
          { _id : 0, host : "localhost:27017"},
          { _id : 1, host : "localhost:27018"}]
	  };
rs.initiate(config);
rs.status();

Step 2. Access the db, insert some document, and check that the replicaSet is working

Open linux terminal connect to primary node, and add the document as follows

use emp;
db.person.insert({"name":"ranjeet"})
db.person.remove({"name":"Tanisha"})

Step 3. Index on the secondary only

  • Step 3.1 Stop secondary mongod on port 27018
    • ps -ef | grep mongod
    • sudo kill pid (for port 27018)
  • Step 3.2 Start secondary without --replSet rs1 and add the index to the collection
  • mongod --logpath "2.log" --dbpath sec --port 27018 --smallfiles --oplogSize 64 --fork
    mongo --port 27018
    use testDB;
    db.person.ensureIndex({"name" : 1});
    db.system.indexes.find();
    

    db.system.indexes.find(); is used to check the newly added index.

  • Step 3.3 Stop the standalone mongod on port 27018
  •  ps -ef | grep mongod
     or 
     ps -A | grep mongod
     sudo kill -9 pid (for port 27018)
    
  • Step 3.4 Start the secondary with the --repSet rs1 Parameter
  •  mongod --replSet rs1 --logpath "2.log" --dbpath sec --port 27018 --smallfiles --oplogSize 64 --fork 
     mongo --port 27018;
     use emp;
     -- check indexes
    

References


Connect with

Leave a Reply

Your email address will not be published. Required fields are marked *