- Installation & Configuration >
- Configuration
Configuration¶
On this page
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”.
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:
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
:
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:
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.
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 Options¶
The following annotated example mongoid.yml
demonstrates how Mongoid
can be configured.
Mongoid delegates to the Ruby driver for client configuration. Please review the driver documentation for details on driver options.
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:
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:
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:
To change the log level, use standard Rails configuration.
Place the following in one of environment configuration files, such as
config/environments/production.rb
:
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:
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:
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:
… or when configuring Mongoid inline:
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:
To change the Ruby driver log level or destination:
To set the driver logger to be the same as the Mongoid logger:
Note
Mongoid does not alter the driver’s logger when running in standalone mode.
Time Zones¶
Ruby has limited time zone support in the standard library. ActiveSupport (which Mongoid depends on) offers more comprehensive time zone support. Importantly, Ruby and ActiveSupport may be configured with different default time zones.
While a thorough treatment of time zones in Ruby is outside the scope of this tutorial, the easiest and most reliable way of achieving correct time zone handling is as follows:
- Set the operating system’s time zone to UTC. For example, on Linux:
- Set ActiveSupport’s time zone to UTC:
- Store and persist all times in UTC. Perform all calculations on times in UTC.
- When working with user input in local time, convert such user input to UTC times as soon as possible, and then work with the UTC times.
- When rendering or otherwise presenting times, convert them to local time after performing all calculations, when actually rendering.
- Date to time (for example, the time when a particular day starts or ends) conversions are a common source of errors. Such conversions should generally be performed while explicitly specifying the time zone in which the date is understood to be.
Applications using Mongoid should generally configure ActiveSupport’s
time zone as described above, and then use Time.zone
rather than Time
(for example, Time.zone.now
instead of Time.now
) to invoke the
ActiveSupport time zone machinery. This also helps achieve correct results
when the system time zone is not UTC, as is common in development environments.
Note that MongoDB stores all times in UTC without time zone information.
Mongoid offers the following time zone-related configuration options:
use_activesupport_time_zone
: If true, prefer to work with times usingActiveSupport::TimeWithZone
. Values in fields of typeTime
will be returned as instances ofActiveSupport::TimeWithZone
. When parsing times without time zone information (such as when mongoizing strings or arrays to time), assume the times are specified in ActiveSupport’s time zone. This is the default.If false, prefer to work with times using Ruby standard library
Time
class. Values in fields of typeTime
will be returned asTime
instances. When parsing times without time zone information, assume the times are specified in the Ruby time zone.Note that the
use_activesupport_time_zone
setting does not affect fields of typesDate
orDateTime
, which useDate
andDateTime
classes for their values, respectively.Also note that Mongoid may still utilize both
Time
andActiveSupport::TimeWithZone
classes internally, as appropriate, regardless of theuse_activesupport_time_zone
setting.use_utc
: If true, times stored in MongoDB will be returned in UTC. If false, times stored in MongoDB will be returned in local time (as instances of eitherTime
orActiveSupport::TimeWithZone
, respectively in the Ruby default time zone or the ActiveSupport time zone, based on the value ofuse_activesupport_time_zone
setting). The default is false.The
use_utc
setting does not affect how times are parsed - parsing is always done in local time when the input being parsed does not include time zone information. To parse dates in UTC, set the system/Ruby or ActiveSupport time zone to UTC (as mentioned above, setting all three to UTC leads to the fewest headaches).Setting
use_activesupport_time_zone
to true andTime.zone
to UTC (and using ActiveSupport time machinery for all time-related operations) is recommended over settinguse_utc
to true.
Note that use_activesupport_time_zone
and use_utc
options do not
throw away time zone information when it is available. For example, a Time
instance does have an associated time zone, and this time zone will be used
even if it is different from ActiveSupport’s configured time zone when
use_activesupport_time_zone
is true.
Configuring SSLContext
¶
It may be desirable to further configure TLS options in your application, for example by enabling or disabling certain ciphers.
This can be done by setting TLS context hooks on the Ruby driver – TLS context
hooks are user-provided Proc``s that will be invoked before any TLS socket
connection in the driver and can be used to modify the underlying
``OpenSSL::SSL::SSLContext
object used by the socket.
To set TLS context hooks, add Proc``s to the ``Mongo.tls_context_hooks
array. This can be done in an initializer. The example below adds a hook
that only enables the “AES256-SHA” cipher.
Every Proc
in Mongo.tls_context_hooks
will be passed an
OpenSSL::SSL::SSLContext
object as its sole argument. These procs will
be executed sequentially during socket creation.
..warning
TLS context hooks are global and will affect all ``Mongo::Client`` instances
in an application.
For more information about TLS context hooks, including best practices for assigning and removing them, see the Ruby driver documentation.
Client-Side Encryption¶
When loading the configuration file, Mongoid permits the file to contain
BSON::Binary
instances which are used for specifying keyId
in
the schema map for client-side encryption,
as the following example shows:
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.
Puma¶
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):
Unicorn¶
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):
Passenger¶
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.
Query Cache Middleware¶
Note
When used with Ruby driver version 2.15 or newer, Mongoid’s Query Cache Middleware delegates to the driver’s Query Cache Middleware.
Mongoid provides a Rack middleware which enables the Query Cache for the duration of each web request. Below is an example of how to enable the Query Cache Middleware in a Ruby on Rails application:
Please refer to the Rails on Rack guide for more information about using Rack middleware in Rails applications.
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: