replication

replica sets

Configuring Mongoid to use a replica set is easy. Simply add an array of host/port pairs to your mongoid.yml with an optional read_secondary option if you want to send reads to slaves. If

hosts:
  - - db1.mongoid.org
    - 27017
  - - db2.mongoid.org
    - 27018
read_secondary: true

If you use Sinatra (or anything other than rails) you need to do make a mongoid.yml like this:

production:
  hosts: [[db1.mongoid.org, 27017], [db2.mongoid.org, 27017]]
  database: project_production
development:
  hosts: [[db1.mongoid.org, 27017], [db2.mongoid.org, 27017]]
  database: project_development

Then in your application load in the settings and configure the connection.

Mongoid.load!("config/mongoid.yml")

To automagically have your models loaded you could do something like this as well:

# load models
$LOAD_PATH.unshift("#{File.dirname(__FILE__)}/models")
Dir.glob("#{File.dirname(__FILE__)}/models/*.rb") do |lib|
  require File.basename(lib, '.*')
end

If you would also like Mongoid to retry operations if a Mongo::ConnectionFailure occurs you may specify this option in your config. Mongoid will retry the operation every half second up to the limit that is set. This defaults to 0.

max_retries_on_connection_failure: 3

Note that Mongoid does not handle reconnection at the time of this documentation, so you'll have to catch the connection errors and retry yourself in the meantime.

master/slave

You can configure Mongoid to do traditional master/slave replication, where reads get round-robined to the slave databases. All is handled through the mongoid.yml once again.

defaults: &defaults
  host: localhost
  slaves:
    - host: localhost
      port: 27018
    - host: localhost
      port: 27019

multiple databases

You can configure Mongoid to use multiple databases on separate servers through the config as well as the model level.

defaults: &defaults
  host: localhost
  slaves:
    - host: localhost
      port: 27018
    - host: localhost
      port: 27019
  databases:
    secondary:
      database: secondary_database
      host: localhost
      port: 27020
      slaves:
        - host: localhost
          port: 27021
        - host: localhost
          port: 27022

To tell a model to use a secondary database, simple tell it at the class level.

class Business
  include Mongoid::Document
  set_database :secondary
end

sharding

If you are using Mongoid in a sharded MongoDB environment and want to tell Mongoid to include the shard keys in it's updates, specify this at the model class level.

class Person
  include Mongoid::Document

  field :first_name, type: String
  field :last_name, type: String

  shard_key :first_name, :last_name
end