Programming for fun and profit

Programming tutorials, problems, solutions. Always with code.

MongoDB 3 replica set configuration

MongoDB 3 Replica Set configuration consists of a few steps and can be done even on a localhost. In this post we show how to configure two node replication.

Quick facts about Replica Sets

  • Replica Set is a set of duplicated nodes.
  • Replica Set nodes can be of different type (see below).
  • Replication in MongoDB is asynchronous.
  • To get configuration of Replica Set use rs.conf() command.
  • To change configuration use rs.reconfig(new_config) command.

Types of Replica Set nodes:

  • Regular: can be come primary and participate in voting
  • Arbiter: only for voting purposes
  • Delayed/Regular: cannot become primary, but can vote (it’s usually for recovery).
  • Hidden: cannot become primary, but can vote (usually analytic node)

Configuration in two steps

Create and start Replica Set nodes

First we have to create directories for separate instances (here two) of MongoDB and start them on different ports (to not clash on localhost):

mkdir -p /tmp/data/rs1 /tmp/data/rs2
mongod --replSet farenda --logpath "1.log" --dbpath /tmp/data/rs1 --port 7017 --oplogSize 64 --smallfiles --fork
mongod --replSet farenda --logpath "2.log" --dbpath /tmp/data/rs2 --port 7018 --oplogSize 64 --smallfiles --fork

Initialize each node with Replica Set parameters

Now we need to inform each node about locations of other Replica Set nodes:

var config = {
  _id: "farenda",
  members: [
    { _id : 0, host : "localhost:7017"}, // the same port as above
    { _id : 1, host : "localhost:7018"}



Share with the World!