Navigation
This version of the documentation is archived and no longer supported.

Configuration

Mongoid is customarily configured through a mongoid.yml file that specifies options and clients. The simplest configuration is as follows, which configures Mongoid to talk to a MongoDB server at “localhost:27017” and use the database named “mongoid”.

development:
  clients:
    default:
      database: mongoid
      hosts:
        - localhost:27017

The top level key in the configuration file, development in the above example, refers to the environment name which the application is executing in, i.e. development, test or production. The third level key, default in the above example, refers to the Mongo client name. Most applications will use a single client named default.

Generating Default Configuration

If you are using Ruby on Rails, you can have Mongoid generate a default configuration file for you by running the following command:

rails g mongoid:config

The configuration file will be placed in config/mongoid.yml.

If you are not using Ruby on Rails, you can copy the minimal configuration given above and save it as config/mongoid.yml.

Loading Mongoid Configuration

If you are using Ruby on Rails, Mongoid configuration is automatically loaded for the current environment as stored in Rails.env when the application loads.

You may need to configure the ORM for your application to be Mongoid by adding the following to application.rb:

config.generators do |g|
  g.orm :mongoid
end

If you are not using Ruby on Rails, Mongoid configuration must be loaded manually. This can be done via the Mongoid.load! method, which takes the configuration file path as its argument, as follows:

# Use automatically detected environment name
Mongoid.load!("path/to/your/mongoid.yml")

# Specify environment name manually
Mongoid.load!("path/to/your/mongoid.yml", :production)

When Mongoid is asked to automatically detect the environment name, it does so by examining the following sources, in order:

  • If Rails top level constant is defined, Rails.env.
  • If Sinatra top level constant is defined, Sinatra::Base.environment.
  • The RACK_ENV environment variable.
  • The MONGOID_ENV environment variable.

It is also possible to configure Mongoid directly in Ruby, without using a configuration file. This configuration style does not support the concept of environments - whatever configuration is provided, it is applied to the current environment - but it does support defining multiple clients.

Mongoid.configure do |config|
  config.clients.default = {
    hosts: ['localhost:27017'],
    database: 'my_db',
  }

  config.log_level = :warn
end

Note

Mongoid must be configured before any component of it is used or referenced. Once a component is used or referenced, changing configuration may not apply changes to already instantiated components.

Mongoid Configuration

The following annotated example mongoid.yml demonstrates how Mongoid can be configured.

development:
  # Configure available database clients. (required)
  clients:
    # Define the default client. (required)
    default:
      # A uri may be defined for a client:
      # uri: 'mongodb://user:password@myhost1.mydomain.com:27017/my_db'
      # Please see driver documentation for details. Alternatively, you can
      # define the following:
      #
      # Define the name of the default database that Mongoid can connect to.
      # (required).
      database: my_db
      # Provide the hosts the default client can connect to. Must be an array
      # of host:port pairs. (required)
      hosts:
        - myhost1.mydomain.com:27017
        - myhost2.mydomain.com:27017
        - myhost3.mydomain.com:27017
      options:
        # These options are Ruby driver options, documented in
        # https://docs.mongodb.com/ruby-driver/current/tutorials/ruby-driver-create-client/

        # Change the default write concern. (default = { w: 1 })
        write:
          w: 1

        # Change the default read preference. Valid options for mode are: :secondary,
        # :secondary_preferred, :primary, :primary_preferred, :nearest
        # (default: primary)
        read:
          mode: :secondary_preferred
          tag_sets:
            - use: web

        # The name of the user for authentication.
        user: 'user'

        # The password of the user for authentication.
        password: 'password'

        # The user's database roles.
        roles:
          - 'dbOwner'

        # Change the default authentication mechanism. Valid options are: :scram,
        # :mongodb_cr, :mongodb_x509, and :plain. (default on 3.0 is :scram, default
        # on 2.4 and 2.6 is :plain)
        auth_mech: :scram

        # The database or source to authenticate the user against. (default: admin)
        auth_source: admin

        # Force the driver to connect in a specific way instead of auto-
        # discovering. Can be one of: :direct, :replica_set, :sharded. Set to :direct
        # when connecting to hidden members of a replica set.
        connect: :direct

        # Change the default time in seconds the server monitors refresh their status
        # via hello commands. (default: 10)
        heartbeat_frequency: 10

        # The time in seconds for selecting servers for a near read preference. (default: 0.015)
        local_threshold: 0.015

        # The timeout in seconds for selecting a server for an operation. (default: 30)
        server_selection_timeout: 30

        # The maximum number of connections in the connection pool. (default: 5)
        max_pool_size: 5

        # The minimum number of connections in the connection pool. (default: 1)
        min_pool_size: 1

        # The time to wait, in seconds, in the connection pool for a connection
        # to be checked in before timing out. (default: 1)
        wait_queue_timeout: 1

        # The time to wait to establish a connection before timing out, in seconds.
        # (default: 10)
        connect_timeout: 10

        # The timeout to wait to execute operations on a socket before raising an error.
        # (default: nil)
        socket_timeout: 5

        # The name of the replica set to connect to. Servers provided as seeds that do
        # not belong to this replica set will be ignored.
        replica_set: my_replica_set

        # Whether to connect to the servers via ssl. (default: false)
        ssl: true

        # The certificate file used to identify the connection against MongoDB.
        ssl_cert: /path/to/my.cert

        # The private keyfile used to identify the connection against MongoDB.
        # Note that even if the key is stored in the same file as the certificate,
        # both need to be explicitly specified.
        ssl_key: /path/to/my.key

        # A passphrase for the private key.
        ssl_key_pass_phrase: password

        # Whether or not to do peer certification validation. (default: true)
        ssl_verify: true

        # The file containing a set of concatenated certification authority certifications
        # used to validate certs passed from the other end of the connection.
        ssl_ca_cert: /path/to/ca.cert

        # Compressors to use. (default is to not use compression)
        compressors: [zlib]

  # Configure Mongoid specific options. (optional)
  options:
    # Include the root model name in json serialization. (default: false)
    include_root_in_json: false

    # Include the _type field in serialization. (default: false)
    include_type_for_serialization: false

    # Preload all models in development, needed when models use
    # inheritance. (default: false)
    preload_models: false

    # Raise an error when performing a #find and the document is not found.
    # (default: true)
    raise_not_found_error: true

    # Raise an error when defining a scope with the same name as an
    # existing method. (default: false)
    scope_overwrite_exception: false

    # Use Active Support's time zone in conversions. (default: true)
    use_activesupport_time_zone: true

    # Ensure all times are UTC in the app side. (default: false)
    use_utc: false

    # Set the Mongoid and Ruby driver log levels when Mongoid is not using
    # Ruby on Rails logger instance. (default: :info)
    log_level: :info

The Ruby driver options may be found in the driver documentation.

ERb Preprocessing

When loading a configuration file, Mongoid processes it with ERb before parsing it as YAML. This allows, for example, constructing the contents of the configuration file at runtime based on environment variables:

development:
  clients:
    default:
      uri: "<%= ENV['MONGODB_URI'] %>"

Note

When outputting values from ERb, ensure the values are valid YAML and escape them as needed.

Note

Since ERb rendering is performed prior to YAML parsing, all ERb directives in the configuration file are evaluated, including those occurring in YAML comments.

Logging

When configuring logging, it is important to keep in mind that Mongoid provides a model layer on top of the MongoDB Ruby driver, and the driver dispatches the CRUD operations to the MongoDB deployment. Therefore, some of the logging output in an application using Mongoid comes from Mongoid itself, and some comes from the driver.

The Mongo client is a Ruby driver client instance, therefore the logger of a Mongo client is the Ruby driver logger, not the Mongoid logger. In other words:

# Ruby driver logger, not Mongoid logger
Mongoid.client(:default).logger

Depending on whether Mongoid is used in a Ruby on Rails application, and how both Mongoid and Ruby driver are configured, they may use the same logger instance or different instances, potentially with different configurations.

In Ruby on Rails Application

When used in a Ruby on Rails application, Mongoid by default inherits the logger and the log level from Rails, and sets the driver’s logger to the same logger instance:

Rails.logger === Mongoid.logger
# => true

Mongoid.logger === Mongo::Logger.logger
# => true

To change the log level, use standard Rails configuration. Place the following in one of environment configuration files, such as config/environments/production.rb:

Rails.application.configure do
  config.log_level = :debug
end

Note

The log_level Mongoid configuration option is not used when Mongoid operates in a Rails application, because Mongoid inherits Rails’ log level in this case.

To configure either Mongoid or driver logger differently from the Rails logger, use an initializer as follows:

Rails.application.configure do
  config.after_initialize do
    # Change Mongoid log destination and/or level
    Mongoid.logger = Logger.new(STDERR).tap do |logger|
      logger.level = Logger::DEBUG
    end

    # Change driver log destination and/or level
    Mongo::Logger.logger = Logger.new(STDERR).tap do |logger|
      logger.level = Logger::DEBUG
    end
  end
end

Note

There is currently no provision in the Ruby standard library Logger to return the log device (i.e. the IO object) that a logger is using. To have, for example, Mongoid and/or the Ruby driver log to the standard Rails log file (e.g. log/development.log) but with a different level from standard Rails logger (Rails.logger), the file must be opened separately and the resulting IO object passed to the Logger constructor.

Note

Since by default Mongoid sets its own logger and the driver’s logger to the same instance as the Rails logger, modifying any of the instances affects all of them. For example the following changes log level for all three loggers, unless the application assigned a separate Logger instance to Mongo::Logger.logger` as described above:

Mongoid::Logger.logger.level = Logger::DEBUG

Standalone

When not loaded in a Ruby on Rails application, Mongoid respects the log_level top level configuration option. It can be given in the configuration file as follows:

development:
  clients:
    default:
      # ...
  options:
    log_level: :debug

… or when configuring Mongoid inline:

Mongoid.configure do |config|
  config.log_level = :debug
end

The default log destination in Mongoid 7.1 and higher is standard error. The default log destination in Mongoid 7.0 and lower is standard output. To change the log destination, create a new logger instance as follows:

Mongoid.logger = Logger.new(STDERR).tap do |logger|
  logger.level = Logger::DEBUG
end

To change the Ruby driver log level or destination:

Mongo::Logger.logger = Logger.new(STDERR).tap do |logger|
  logger.level = Logger::DEBUG
end

To set the driver logger to be the same as the Mongoid logger:

Mongo::Logger.logger = Mongoid.logger

Note

Mongoid does not alter the driver’s logger when running in standalone mode.

Usage with Forking Servers

When using Mongoid with a forking web server such as Puma, Unicorn or Passenger, it is recommended to not perform any operations on Mongoid models in the parent process prior to the fork.

When a process forks, Ruby threads are not transferred to the child processes and the Ruby driver Client objects lose their background monitoring. The application will typically seem to work just fine until the deployment state changes (for example due to network errors, a maintenance event) at which point the application is likely to start getting NoServerAvailable exception when performing MongoDB operations.

If the parent process needs to perform operations on the MongoDB database, reset all clients in the workers after they forked. How to do so depends on the web server being used.

If the parent process does not need to perform operations on the MongoDB database after child processes are forked, close the clients in the parent prior to forking children. If the parent process performs operations on a Mongo client and does not close it, the parent process will continue consuming a connection slot in the cluster and will continue monitoring the cluster for as long as the parent remains alive.

Note

The close/reconnect pattern described here should be used with Ruby driver version 2.6.2 or higher. Previous driver versions did not recreate monitoring threads when reconnecting.

Use the on_worker_boot hook to reconnect clients in the workers and the before_fork hook to close clients in the parent process (`Puma documentation <<https://puma.io/puma/>`_):

on_worker_boot do
  Mongoid::Clients.clients.each do |name, client|
    client.close
    client.reconnect
  end
end

before_fork do
  Mongoid.disconnect_clients
end

Use the after_fork hook to reconnect clients in the workers and the before_fork hook to close clients in the parent process (Unicorn documentation):

after_fork do |server, worker|
  Mongoid::Clients.clients.each do |name, client|
    client.close
    client.reconnect
  end
end

before_fork do |server, worker|
  Mongoid.disconnect_clients
end

Use the starting_worker_process hook to reconnect clients in the workers (Passenger documentation). Passenger does not appear to have a hook that is invoked in the parent process before the workers are forked.

if defined?(PhusionPassenger)
  PhusionPassenger.on_event(:starting_worker_process) do |forked|
    Mongoid::Clients.clients.each do |name, client|
      client.close
      client.reconnect
    end
  end
end

Development Configuration

Driver’s default configuration is suitable for production deployment. In development, some settings can be adjusted to provide a better developer experience.

  • :server_selection_timeout: set this to a low value (e.g., 1)

if your MongoDB server is running locally and you start it manually. A low server selection timeout will cause the driver to fail quickly when there is no server running.

Sample recommended development configuration:

development:
  clients:
    default:
      database: mongoid
      hosts:
        - localhost:27017
      options:
        server_selection_timeout: 1
←   Installation Documents  →