Docs Menu

Application Configuration

In this guide, you can learn how to configure how your application connects to MongoDB and how it processes your data. When you set up your application, you are required to supply a connection string, or connection URI, which contains a set of instructions that Mongoid uses to connect to a MongoDB. To learn more about connection strings, see Connection Strings in the Server manual.

You primarily configure Mongoid by using a mongoid.yml file that specifies your connection options and clients. To learn more about creating a mongoid.yml file when setting up an application, see one of the following guides:

The simplest configuration for an application configures Mongoid to connect to a MongoDB server at localhost:27017 and access the database named myDB. The mongoid.yml file for this configuration resembles the following file:

mongoid.yml
development:
clients:
default:
database: myDB
hosts:
- localhost:27017

The top level key in the preceding file, development, refers to the environment name which the application is running. Possible values include development, test or production. The third level key, default, refers to the MongoDB client name. Most applications use a single client named default.

If you are using Ruby on Rails as your application framework, you can generate a default configuration file in your application by running the following shell command:

rails g mongoid:config

This command creates the configuration file at config/mongoid.yml. An initializer is also created at config/initializers/mongoid.rb. We recommended that you specify all settings in mongoid.yml, but you can also use the mongoid.rb initializer to set configuration options. Settings in mongoid.yml always override settings in the initializer.

If you are not using Ruby on Rails, you can create the config/mongoid.yml file, then copy and paste the configuration file shown in the preceding section.

Important

You must configure Mongoid before using any Mongoid component. After you use or reference a component, changing the configuration might not apply changes to already instantiated components.

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

You can also specify Mongoid as the ORM for your application by adding the following lines to your application.rb file:

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

If you are not using Ruby on Rails, you must load your Mongoid configuration manually. Call the Mongoid.load! method, which takes the configuration file path as its argument:

# Uses automatically detected environment name
Mongoid.load!("config/mongoid.yml")
# Specifies environment name manually
Mongoid.load!("config/mongoid.yml", :development)

Mongoid detects the environment name by examining the following sources, in order:

  1. If Rails top-level constant is defined: Rails.env

  2. If Sinatra top-level constant is defined: Sinatra::Base.environment

  3. RACK_ENV environment variable

  4. MONGOID_ENV environment variable.

Note

You can also configure Mongoid directly in Ruby without using a configuration file. This configuration style does not support the concept of environments. Any configuration that you provide is applied to the current environment.

The following annotated example mongoid.yml file describes where to set each type of configuration option and provides information about each option and its parameters.

development:
# Configures available database clients. (required)
clients:
# Defines the default client. (required)
default:
# Supplies your connection URI, including the database name.
uri: mongodb+srv://user:pass@mongo0.example.com/myDB
# OR, you can define the parameters separately.
# Defines the name of the default database. (required)
database: my_db_development
# Provides the hosts the client can connect to.
# Must be an array of host:port pairs. (required)
hosts:
- localhost:27017
options:
# All options in this section are Ruby driver client options.
# To learn more, visit
# https://www.mongodb.com/docs/ruby-driver/current/reference/create-client/
# Sets the write concern. (default = { w: 1 })
write:
w: 1
# Sets the read preference. Valid options for mode are: :secondary,
# :secondary_preferred, :primary, :primary_preferred, :nearest
# (default: primary)
read:
mode: :secondary_preferred
tag_sets: # If using tag sets
- use: web
# Sets name of the user for authentication.
user: "user"
# Sets password of the user for authentication.
password: "password"
# Sets user's database roles.
roles:
- "dbOwner"
# Sets the authentication mechanism. Valid options include:
# :scram, :scram256, :mongodb_cr, :mongodb_x509, :gssapi, :aws, :plain
# MongoDB Server defaults to :scram
auth_mech: :scram
# Sets the database or source to authenticate the user against.
# (default: the database specified above or admin)
auth_source: admin
# Specifies type of connection. Can be one of: :direct,
# :replica_set, :sharded
# Set to :direct when connecting to hidden members of a replica set.
connect: :direct
# Changes the time taken for the server monitors to refresh
# their status via hello commands. (default: 10)
heartbeat_frequency: 10
# Sets time in seconds for selecting servers for a :nearest read
# preference. (default: 0.015)
local_threshold: 0.015
# Sets timeout in seconds for selecting a server for an
# operation. (default: 30)
server_selection_timeout: 30
# Sets maximum number of connections in the connection pool.
# (default: 5)
max_pool_size: 5
# Sets minimum number of connections in the connection pool.
# (default: 1)
min_pool_size: 1
# Sets time to wait, in seconds, in the connection pool for a
# connection to be checked in before timing out. (default: 5)
wait_queue_timeout: 5
# Sets time to wait to establish a connection before timing out,
# in seconds. (default: 10)
connect_timeout: 10
# Sets name of the replica set to connect to. Servers provided as
# seeds that do not belong to this replica set are ignored.
replica_set: myRS
# Sets compressors to use for wire protocol compression.
# (default is to not use compression)
compressors: ["zstd", "snappy", "zlib"]
# Specified whether to connect to the servers by using ssl.
# (default: false)
ssl: true
# Sets certificate file used to identify the connection for SSL.
ssl_cert: /path/to/my.cert
# Sets private keyfile used to identify the connection against MongoDB.
# 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
# Sets passphrase for the private key.
ssl_key_pass_phrase: password123
# Specifies whether to do peer certification validation.
# (default: true)
ssl_verify: true
# Sets file containing concatenated certificate authority
# certificates used to validate certs passed from the other end
# of the connection.
ssl_ca_cert: /path/to/ca.cert
# Specifies whether to truncate long log lines. (default: true)
truncate_logs: true
# Optional Mongoid-specific configuration.
options:
# Allows BSON::Decimal128 to be parsed and returned directly in
# field values. Only has effect when BSON 5+ is present.
allow_bson5_decimal128: false
# Sets app name that is printed to the MongoDB logs upon establishing
# a connection. Value is used as the database name if the database
# name is not provided. (default: nil)
app_name: nil
# When false, callbacks for embedded documents will not be
# called. This is the default in 9.0.
# Setting this flag to true restores the pre-9.0 behavior, where callbacks
# for embedded documents are called, which might lead to stack overflow errors.
around_callbacks_for_embeds: false
# Sets the async_query_executor for the application. By default the
# thread pool executor is set to :immediate. Options are:
# - :immediate - Initializes a single +Concurrent::ImmediateExecutor+
# - :global_thread_pool - Initializes a single +Concurrent::ThreadPoolExecutor+
# that uses the +async_query_concurrency+ for the +max_threads+ value.
async_query_executor: :immediate
# Marks belongs_to associations as required by default, so saving a
# model with a missing association triggers a validation error.
belongs_to_required_by_default: true
# Sets the global discriminator key.
discriminator_key: "_type"
# Raises an exception when a field is redefined.
duplicate_fields_exception: false
# Defines how many asynchronous queries can be executed concurrently.
# This option should be set only if `async_query_executor` is set
# to `:global_thread_pool`.
global_executor_concurrency: nil
# When this flag is true, any attempt to change the _id of a persisted
# document will raise an exception (Errors::ImmutableAttribute).
# This is the default in 9.0. Setting this flag to false restores the
# pre-9.0 behavior, where changing the _id of a persisted
# document might be ignored.
immutable_ids: true
# Includes the root model name in json serialization.
include_root_in_json: false
# # Include the _type field in serialization.
include_type_for_serialization: false
# Specifies whether to join nested persistence contexts for atomic
# operations to parent contexts.
join_contexts: false
# When this flag is false (the default for 9.0), a document that
# is created or loaded remembers the storage options that were active
# when it was loaded, and will use those same options by default when
# saving or reloading itself.
#
# When this flag is true, a document does not remember the storage
# options from when it was loaded/created, and
# subsequent updates will need to explicitly set up those options
# each time.
legacy_persistence_context_behavior: false
# Specifies whether to use legacy read-only behavior. To learn more,
# visit https://www.mongodb.com/docs/mongoid/current/interact-data/crud
legacy_readonly: false
# Sets the log level. This must be set before referencing clients
# or Mongo.logger, because changes to this option are not be
# propagated to any clients and loggers that already exist.
log_level: :info
# Stores BigDecimals as Decimal128s instead of strings in the db.
map_big_decimal_to_decimal128: true
# Preloads all models in development, needed when models use
# inheritance.
preload_models: false
# When this flag is true, callbacks for every embedded document will be
# called only once, even if the embedded document is embedded in multiple
# documents in the root document's dependencies graph.
# This is the default in 9.0. Setting this flag to false restores the
# pre-9.0 behavior, where callbacks are called for every occurrence of an
# embedded document.
prevent_multiple_calls_of_embedded_callbacks: true
# Raises an error when performing a find operation and no document
# matches.
raise_not_found_error: true
# Raises an error when defining a scope with the same name as an
# existing method.
scope_overwrite_exception: false
# Returns stored times as UTC.
use_utc: false
# Optional driver-specific configuration.
driver_options:
# When this flag is off, an aggregation done on a view is performed on
# the documents included in that view, instead of all documents in the
# collection. When this flag is on, the view filter is ignored.
broken_view_aggregate: true
# When this flag is set to false, the view options is correctly
# propagated to readable methods.
broken_view_options: true
# When this flag is set to true, the update and replace methods
# validate the parameters and raise an error if they are invalid.
validate_update_replace: false

Mongoid supports setting configuration options to their default values for specific versions. This might be useful for when you update to a new Mongoid version. When upgrading your Mongoid version, set the following options on Mongoid::Config:

Mongoid.configure do |config|
config.load_defaults <older version>
end

This allows you to upgrade to a new version of Mongoid while using the configuration options from the previous installed version. This feature gives you more time to implement tests for each changed behavior to make sure your code doesn't break or behave in unexpected ways. After you verify that your application works as expected, you can remove this code to use the current version's default configuration.

When loading a configuration file, Mongoid processes it by using ERb before parsing it as YAML. This allows Mongoid to construct the contents of the configuration file at runtime based on environment variables.

Because Mongoid performs ERb rendering before YAML parsing, all ERb directives in the configuration file are evaluated, including those occurring in YAML comments.

The following sample mongoid.yml file demonstrates how you can reference an environment variable that stores your connection string:

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

Tip

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

Mongoid uses Active Support's time zone functionality, which provides more functionality than Ruby's standard library. Active Support allows configuration of the Time.zone variable, a thread-global variable which provides context for working with date and time values.

You can implement correct time zone handling in your application by performing the following steps:

  1. Set the operating system's time zone to UTC.

  2. Set your application default time zone to UTC, as shown in the following code:

    # If using Rails, in `application.rb`:
    class Application < Rails::Application
    config.time_zone = 'UTC'
    end
    # If not using Rails:
    Time.zone = 'UTC'
  3. In each controller and job class, set the appropriate time zone in a before_filter callback:

    class ApplicationController < ActionController::Base
    before_filter :fetch_user, :set_time_zone
    def set_time_zone
    Time.zone = @user.time_zone
    end
    end
  4. Then, you can work with times in the local time zone.

  5. Use Active Support methods instead of the Ruby standard library.

    • Use the Time.zone.now or Time.current methods instead of Time.now

    • Use the Date.current method instead of Date.today

    The Ruby standard library methods such as Time.now and Date.today reference your system time zone and not the value of the Time.zone variable.

    You might mistake these similarly named methods, so we recommend using the Rails/TimeZone feature from RuboCop in your tests.

MongoDB stores all times in UTC without time zone information. Mongoid models load and return time values as instances of ActiveSupport::TimeWithZone. You can set the use_utc option to control how Mongoid sets the time zone when loading values from the database:

  • false (default): Mongoid uses the value of Time.zone to set the time zone of values from the database.

  • true: Mongoid always sets the time zone as UTC on loaded time values.

The use_utc option affects only how data is loaded and does not affect how data is persisted. For example, if you assign a Time or ActiveSupport::TimeWithZone instance to a time field, the time zone information of the assigned instance is used regardless of the use_utc value.

Alternatively, if you assign a string value to a time field, any time zone information in the string is parsed. If the string does not include time zone information it is parsed according to the Time.zone value.

The following code sets a Time.zone value and demonstrates how Mongoid processes different time strings:

Time.use_zone("Asia/Kolkata") do
# String does not include time zone, so "Asia/Kolkata" is used
ghandi.born_at = "1869-10-02 7:10 PM"
# Time zone in string (-0600) is used
amelia.born_at = "1897-07-24 11:30 -0600"
end

You can configure advanced TLS options in your application, such as enabling or disabling certain ciphers. To learn about the main SSL/TLS options, see the Configuration Options section of this guide.

You can set TLS context hooks on the Ruby driver. TLS context hooks are user-provided Proc objects that are invoked before any TLS socket connection is created in the driver. These hooks can be used to modify the underlying OpenSSL::SSL::SSLContext object used by the socket.

To set TLS context hooks, add a Proc to the Mongo.tls_context_hooks array. This task can be done in an initializer. The following example adds a hook that only enables the "AES256-SHA" cipher:

Mongo.tls_context_hooks.push(
Proc.new { |context|
context.ciphers = ["AES256-SHA"]
}
)

Every Proc in Mongo.tls_context_hooks is passed an OpenSSL::SSL::SSLContext object as its sole argument. These Proc objects are run sequentially during socket creation.

Warning

TLS context hooks are global and affect all Mongo::Client instances in an application.

To learn more about TLS context hooks, see Modifying SSLContext in the Ruby driver documentation.

Mongoid supports compression of messages to and from MongoDB. This functionality is provided by the Ruby driver, which implements the following supported algorithms:

  • Zstandard (Recommended): To use zstandard compression, you must install the zstd-ruby library. This compressor produces the highest compression at the same CPU consumption compared to the other compressors.

  • Snappy: To use snappy compression, you must install the snappy library.

  • Zlib: To use zlib compression, you must install the zlib library.

To use wire protocol compression, configure the driver options in your mongoid.yml file:

development:
clients:
default:
...
options:
# Specify compresses to use. (default is no compression)
# Accepted values are zstd, zlib, snappy, or a combination
compressors: ["zstd", "snappy"]

If you do not explicitly request any compressors, the driver does not use compression, even if the required dependencies for one or more compressors are installed.

The driver chooses the first compressor, if you specify multiple, that is supported by your MongoDB deployment.