MongoDB Replica Sets

Published: 25 May 2012

This blog post demonstrates how to set up Replica Sets in MongoDB. Replica Sets is a way to get High Availability (HA) in MongoDB without much hassle. To be able to use a slave for reads, backups or as a standby master we use the MongoDB Replica Sets.

This post is mostly for my own future reference.

Upgrade to replica sets

First, we have to upgrade to replica sets. This is done by doing the following on a single node configuration.

On the MongoDB nodes, shut down the MongoDB service and start it with the following command (fooReplicaSet is the replica set name):

mongod --replSet fooReplicaSet

Config files

To add replSet in configuration files, add replSet = fooReplicaSet into configuration (such as /etc/mongodb.conf).

Check Status

Check replica set status by running:


Information about states is located in the MongoDB documentation.

Adding members

To add members in the replica set we can do it by adding all the nodes via rs.initiate().

> c = {
... _id : "setName",
... members : [
... { _id : 0, host : "" },
... { _id : 1, host : "" },
... { _id : 2, host : "" } ] }
> rs.initiate(c)
> rs.status()

This will initiate and add the nodes, and

Why can't I query the slave?

The error, error: { "$err" : "not master", "code" : 10107 } may occur when reading from a slave, in that case you have to enable slaveOk.



When using replica sets, we are able to do backups or store a database for DR.

If the master gets unavailable a new master will be elected. This will be a way to support automated failover and HA.

Not using Replica Sets is a dangerous business but is of course no silver bullet. As the CAP theorem states:

According to the theorem, a distributed system can satisfy any two of these [Consistency, Availability, Partition Tolerance] guarantees at the same time, but not all three.

The MongoDB replica sets will only satisfy Availability and Partition Tolerance (AP) but should be good enough for many systems.