Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 24 additions & 2 deletions source/configuration.txt
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,31 @@ Configuration
.. toctree::
:caption: Configuration

Application Configuration </configuration/app-config>
Persistence Targets </configuration/persistence-config>
Sharding </configuration/sharding>
Logging </configuration/logging-config>
Query Cache Middleware </configuration/query-cache-config>
Forking Servers </configuration/forking-server-config>

.. Collection Configuration </configuration/collection-config>

In this section, you can learn how to configure different options with {+odm+}.

- :ref:`Sharding Configuration <mongoid-sharding-configuration>`: Learn how to configure
sharding in your {+odm+} application.
- :ref:`mongoid-app-config`: Learn about settings you can use to
customize how your application works with MongoDB.

- :ref:`mongoid-persistence`: Learn how to use {+odm+} to view and
customize your document storage.

- :ref:`mongoid-sharding-configuration`: Learn how to configure
sharding in your application.

- :ref:`mongoid-logging-config`: Learn how to configure loggers in your
application.

- :ref:`mongoid-query-cache-config`: Learn how to implement query cache
middleware in your application.

- :ref:`mongoid-forking-server-config`: Learn how to configure your
application to use a forking web server.
362 changes: 362 additions & 0 deletions source/configuration/app-config.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,362 @@
.. _mongoid-app-config:

=========================
Application Configuration
=========================

.. facet::
:name: genre
:values: reference

.. meta::
:keywords: code example, customize, behavior

.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol

Overview
--------

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 {+odm+} uses to
connect to a MongoDB. To learn more about connection strings, see
:manual:`Connection Strings </reference/connection-string/>` in the
{+server-manual+}.

You primarily configure {+odm+} 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:

- :ref:`mongoid-quick-start-rails`
- :ref:`mongoid-quick-start-sinatra`

Structure of mongoid.yml
------------------------

The simplest configuration for an application configures {+odm+} 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:

.. code-block:: yaml
:caption: 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``.

Generate Default Configuration
------------------------------

If you are using {+ror+} as your application framework, you can generate
a default configuration file in your application by running the
following shell command:

.. code-block:: bash

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 {+ror+}, you can create the ``config/mongoid.yml``
file, then copy and paste the configuration file shown in the preceding
section.

Load {+odm+} Configuration
--------------------------

.. important::

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

If you are using {+ror+}, Rails automatically loads your {+odm+}
configuration for the current environment as stored in ``Rails.env``.

You can also specify {+odm+} as the ORM for your application by
adding the following lines to your ``application.rb`` file:

.. code-block:: ruby

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

If you are not using {+ror+}, you must load your {+odm+} configuration
manually. Call the ``Mongoid.load!`` method, which takes the
configuration file path as its argument:

.. code-block:: ruby

# Uses automatically detected environment name
Mongoid.load!("config/mongoid.yml")

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

{+odm+} detects the environment name by examining the following sources,
in order:

1. If ``Rails`` top-level constant is defined: ``Rails.env``
#. If ``Sinatra`` top-level constant is defined: ``Sinatra::Base.environment``
#. ``RACK_ENV`` environment variable
#. ``MONGOID_ENV`` environment variable.

.. note::

You can also configure {+odm+} directly in {+language+} 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.

.. _mongoid-config-options-all:

Configuration Options
---------------------

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.

.. literalinclude:: /includes/configuration/sample-config-options.yml
:language: yaml

Version Based Defaults
----------------------

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

.. code-block:: ruby

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

This allows you to upgrade to a new version of {+odm+} 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.

ERb Pre-processing
------------------

When loading a configuration file, {+odm+} processes it by using
:github:`ERb <ruby/erb>` before parsing it as YAML. This allows {+odm+}
to construct the contents of the configuration file at runtime
based on environment variables.

Because {+odm+} 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:

.. code-block:: yaml

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-config-time-zones:

Time Zone Configuration
-----------------------

{+odm+} uses Active Support's time zone functionality, which provides
more functionality than {+language+}'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.

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

.. code-block:: ruby

# If using Rails, in `application.rb`:
class Application < Rails::Application
config.time_zone = 'UTC'
end

# If not using Rails:
Time.zone = 'UTC'

#. In each controller and job class, set the appropriate time zone in a
``before_filter`` callback:

.. code-block:: ruby

class ApplicationController < ActionController::Base
before_filter :fetch_user, :set_time_zone

def set_time_zone
Time.zone = @user.time_zone
end
end

#. Then, you can work with times in the local time zone.

#. Use Active Support methods instead of the {+language+} 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 {+language+} 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
<https://docs.rubocop.org/rubocop-rails/cops_rails.html#railstimezone>`__
feature from RuboCop in your tests.

Set Time Zone on MongoDB Data
-----------------------------

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

- ``false`` (*default*): {+odm+} uses ``Time.zone`` to set the time
zone of time values are loaded from database.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's a few ways this could be corrected. This is my best guess:

Suggested change
- ``false`` (*default*): {+odm+} uses ``Time.zone`` to set the time
zone of time values are loaded from database.
- ``false`` (*default*): {+odm+} uses ``Time.zone`` to set the time
zone as time values are loaded from the database.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed

- ``true``: {+odm+} 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
{+odm+} processes different time strings:

.. code-block:: ruby

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"

Check failure on line 282 in source/configuration/app-config.txt

View workflow job for this annotation

GitHub Actions / TDBX Vale rules

[vale] reported by reviewdog 🐶 [MongoDB.Time24h2Digits] Show the hours, minutes, and seconds with two digits each, even if the leading digit is 0 ('7:10'). Raw Output: {"message": "[MongoDB.Time24h2Digits] Show the hours, minutes, and seconds with two digits each, even if the leading digit is 0 ('7:10').", "location": {"path": "source/configuration/app-config.txt", "range": {"start": {"line": 282, "column": 35}}}, "severity": "ERROR"}

# Time zone in string (-0600) is used
amelia.born_at = "1897-07-24 11:30 -0600"
end

SSL/TLS Configuration
---------------------

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 :ref:`mongoid-config-options-all` 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, which can be done in an initializer. The following example adds a hook
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems a bit awkward:

Suggested change
To set TLS context hooks, add a ``Proc`` to the ``Mongo.tls_context_hooks``
array, which can be done in an initializer. The following example adds a hook
To set TLS context hooks, add a ``Proc`` to the ``Mongo.tls_context_hooks``
array. This can be done in an initializer. The following example adds a hook

that only enables the ``"AES256-SHA"`` cipher:

.. code-block:: ruby

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 :ruby:`Modifying SSLContext
</reference/create-client/#modifying-sslcontext>` in the {+ruby-driver+}
documentation.

Network Compression
-------------------

{+odm+} supports compression of messages to and from MongoDB. This
functionality is provided by the {+ruby-driver+}, which implements the
following supported algorithms:

- :github:`Snappy <google/snappy>`: To use ``snappy`` compression, you
must install the `snappy <https://rubygems.org/gems/snappy>`__ library.
- `Zlib <https://zlib.net/>`__: To use ``zlib`` compression, you
must install the `zlib <https://rubygems.org/gems/zlib>`__ library.
- `Zstandard <https://facebook.github.io/zstd/>`__: To use ``zlib``
compression, you must install the `zstd-ruby
<https://rubygems.org/gems/zstd-ruby>`__ library.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Move this to the top of the list since it's our recommendation:

Suggested change
- `Zstandard <https://facebook.github.io/zstd/>`__: To use ``zlib``
compression, you must install the `zstd-ruby
<https://rubygems.org/gems/zstd-ruby>`__ library.
- `Zstandard <https://facebook.github.io/zstd/>`__ (recommended): To use ``zlib``
compression, you must install the `zstd-ruby
<https://rubygems.org/gems/zstd-ruby>`__ library.
- produces the highest compression with the same CPU consumption


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

.. code-block:: yaml

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

Check failure on line 359 in source/configuration/app-config.txt

View workflow job for this annotation

GitHub Actions / TDBX Vale rules

[vale] reported by reviewdog 🐶 [MongoDB.CommaRestrictiveClause] Don’t use a comma to set off a restrictive clause (one that begins with that). Raw Output: {"message": "[MongoDB.CommaRestrictiveClause] Don’t use a comma to set off a restrictive clause (one that begins with that).", "location": {"path": "source/configuration/app-config.txt", "range": {"start": {"line": 359, "column": 65}}}, "severity": "ERROR"}
is supported by the MongoDB Server. We recommend using the ``zstd``
compressor because it produces the highest compression at the same CPU
consumption compared to the other compressors.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add this recommendation into the list above.

Suggested change
is supported by the MongoDB Server. We recommend using the ``zstd``
compressor because it produces the highest compression at the same CPU
consumption compared to the other compressors.
is supported by the MongoDB Server.

Loading
Loading