Rails + MongoDB ReplicaSet Configuration

This article shows how to configure a Ruby on Rails app for a MongoDB ReplicaSet. How to set up a MongoDB ReplicaSet I described here: MongoDB ReplicaSet Tutorial. And how to configure Rails to work together with MongoDB is described here: Rails + MongoDB Quickstart Tutorial.

If you want to connect to a ReplicaSet you just have to change your configuration a little bit. This is how your mongoid.yml file should look like:

  database: mydb_prod
    - - mongonode1:1222
    - - mongonode2:1222
    - - mongonode3:1222
  read: :secondary

“mongonode1”, “mongonode2” and “mongonode3” should be mapped to a real ip address, of course! Usually you do that in “/etc/hosts”.

You don’t have to define a PRIMARY! The driver will figure out which of them is the PRIMARY. I like this! You also don’t need a load balancer. Because all nodes are known by the driver. And so the driver will figure it out.

The property “read” can have 2 values: [“:secondary”, “:primary”]. “:secondary” means that read operations can also be routed to secondary nodes. “:primary” means that all read operations will be routed to the PRIMARY node.

Published by Robert Reiz

CEO @ VersionEye. Passionated software developer since 1998.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: