Docs Menu

アプリケーション構成

このガイドでは、アプリケーションでMongoDBに接続し、データを処理する方法を構成する方法を学習できます。 アプリケーションを設定するときは、Mongoid がMongoDBに接続するために使用する指示のセットを含む接続文字列、または接続 URI を指定する必要があります。接続文字列の詳細については、サーバー マニュアルの「 接続文字列 」を参照してください。

Mongoid は主に、接続オプションとクライアントを指定する mongoid.ymlファイルを使用して Mongoid を構成します。 アプリケーションを設定するときに mongoid.ymlファイルを作成する方法の詳細については、次のいずれかのガイドを参照してください。

アプリケーションの最も単純な構成では、Mongoid は localhost:27017 のMongoDBサーバーに接続し、myDB という名前のデータベースにアクセスするように構成されます。 この構成の mongoid.ymlファイルは次のファイルに似ています。

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

前述のファイルの最上位キー(development)は、アプリケーションがを実行中環境名を参照します。 可能な値は developmenttest、または production です。 3 つ目のレベルキー default は、 MongoDBクライアント名を参照します。 ほとんどのアプリケーションは default という名前の単一のクライアントを使用します。

アプリケーションフレームワークとしてRuby on Rails を使用している場合は、次のシェルコマンドを実行中てアプリケーションにデフォルトの構成ファイル を生成できます。

rails g mongoid:config

このコマンドは、config/mongoid.yml に構成ファイルを作成します。 初期化子も config/initializers/mongoid.rb に作成されます。 mongoid.yml ですべての設定を指定することを推奨しますが、mongoid.rb 初期化オプションを使用して構成オプションを設定することもできます。 mongoid.yml の設定は、常に初期化設定の設定を上書きします。

Ruby on Rails を使用していない場合は、 config/mongoid.ymlファイルを作成し、前のセクションに表示されている構成ファイルをコピーして貼り付けることができます。

重要

Mongoid コンポーネントを使用する前に、Mongoid を設定する必要があります。 コンポーネントを使用した後、または参照後、構成を変更しても、すでにインスタンス化されているコンポーネントには変更が適用されない可能性があります。

Ruby on Rails を使用している場合、Rails は Rails.env に保存されている現在の環境の Mongoid 構成を自動的に読み込みます。

また、 application.rbファイルに次の行を追加することで、アプリケーションの ORM として Mongoid を指定できます。

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

Ruby on Rails を使用していない場合は、Mongoid 構成を手動でロードする必要があります。 構成ファイルパスを引数として受け取る Mongoid.load! メソッドを呼び出します。

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

Mongoid は、次のソースを順番に検査して環境名を検出します。

  1. Rails の最上位定数が定義されている場合: Rails.env

  2. Sinatra の最上位定数が定義されている場合: Sinatra::Base.environment

  3. RACK_ENV 環境変数

  4. MONGOID_ENV 環境変数。

注意

構成ファイル を使用せずに、 Rubyで Mongoid を直接構成することもできます。 この構成スタイルは、環境の概念をサポートしていません。 指定した構成はすべて現在の環境に適用されます。

次の注釈付きの mongoid.ymlファイルの例では、各タイプの構成オプションを設定する場所を説明し、各オプションとそのパラメーターに関する情報を提供しています。

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/ja-jp/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/ja-jp/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 は、特定のバージョンに対して構成オプションをデフォルト値に設定することをサポートしています。 これは、新しい Mongoid バージョンに更新するときに役立つ場合があります。 Mongoid のバージョンをアップグレードするときは、Mongoid::Config で次のオプションを設定します。

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

これにより、以前にインストールされたバージョンの構成オプションを使用しながら、Mongoid の新しいバージョンにアップグレードできます。 この機能により、変更された動作ごとにテストを実装して、コードが中断されたり、予期しない方法で動作したりしないことを確認できます。 アプリケーションが期待どおりに動作することを確認した後、このコードを削除して現在のバージョンのデフォルト構成を使用できます。

構成ファイル を読み込むと、Mongoid は YAML として解析する前に ERb を使用して処理します。これにより、Mongoid は環境変数に基づいて実行時に構成ファイルの内容を構築できます。

Mongoid は YAML 解析前に ERb レンダリングを実行するため、構成ファイル内のすべての ERb ディレクティブ(YAML コメントに発生するものを含む)が評価されます。

次のサンプルmongoid.ymlファイルは、接続文字列 を保存する環境変数を参照方法を示しています。

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

Tip

ERb から値を出力するときは、値が有効な YAML であることを確認し、必要に応じてエスケープします。

Mongoid は Active Directory のタイムゾーン機能を使用しています。これは Ruby の標準ライブラリよりも多くの機能を提供します。 アクティブなサポートでは、日付と時刻の値を操作するためのコンテキストを提供するスレッドグローバル変数である Time.zone 変数を構成できます。

次の手順を実行することで、アプリケーションに正しいタイムゾーン処理を実装できます。

  1. オペレーティング システムのタイムゾーンを UTC に設定します。

  2. 次のコードに示すように、アプリケーションのデフォルトのタイムゾーンを UTC に設定します。

    # If using Rails, in `application.rb`:
    class Application < Rails::Application
    config.time_zone = 'UTC'
    end
    # If not using Rails:
    Time.zone = 'UTC'
  3. 各 コントローラー とジョブクラスで、 before_filterコールバックで適切なタイムゾーンを設定します。

    class ApplicationController < ActionController::Base
    before_filter :fetch_user, :set_time_zone
    def set_time_zone
    Time.zone = @user.time_zone
    end
    end
  4. その後、 ローカル タイムゾーン内の時間で作業できるようになります。

  5. Ruby標準ライブラリではなく、アクティブ サポート メソッドを使用します。

    • Time.now の代わりに Time.zone.now メソッドまたは Time.current メソッドを使用します

    • Date.today ではなく Date.current メソッドを使用する

    Time.nowDate.today などのRuby の標準ライブラリ メソッドは、Time.zone 変数の値ではなく、システム タイムゾーンを参照。

    これらの名前の似たメソッドを混同する可能性があるため、テストでは RuboCop の Rails/TimeZone 機能を使用することをお勧めします。

MongoDB は、タイムゾーン情報なしですべての時間を UTC で保存します。 Mongoid モデルは時間値を ActiveSupport::TimeWithZone のインスタンスとして読み込み、返します。 データベースから値を読み込むときに、Mongoid がタイムゾーンを設定する方法を制御するには、use_utc オプションを設定します。

  • false (デフォルト): Mongoid はTime.zone の値を使用して、データベースから値のタイムゾーンを設定します。

  • true: Mongoid は、読み込まれた時間値のタイムゾーンを常に UTC として設定します。

use_utc オプションはデータのロード方法のみに影響し、データの永続化方法には影響しません。 例、 Time または ActiveSupport::TimeWithZoneインスタンスを時間フィールドに割り当てると、use_utc 値に関係なく、割り当てられたインスタンスのタイムゾーン情報が使用されます。

あるいは、 時間フィールドに string の値を割り当てると、string 内のすべてのタイムゾーン情報が解析されます。 string にタイムゾーン情報が含まれていない場合は、Time.zone 値に従って解析されます。

次のコードは、Time.zone 値を設定し、Mongoid がさまざまな時間文字列を処理する方法を示しています。

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

アプリケーション内で特定の暗号を有効または無効にするなど、高度な TLS オプションを構成できます。 主要な SSL/TLS オプションの詳細については、このガイドの「 構成オプション 」セクションを参照してください。

Rubyドライバーで TLS コンテキスト フックを設定できます。 TLS コンテキスト フックは、ドライバーで TLS ソケット接続が作成される前に呼び出されるユーザー提供の Proc オブジェクトです。 これらのフックは、ソケットで使用される基礎の OpenSSL::SSL::SSLContextオブジェクトを変更するために使用できます。

TLS コンテキスト フックを設定するには、Mongo.tls_context_hooks 配列に Proc を追加します。 このタスクは初期化 で実行できます。 次の例では、 "AES256-SHA" 暗号のみを有効にするフックを追加します。

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

Mongo.tls_context_hooks 内のすべての Proc には、OpenSSL::SSL::SSLContextオブジェクトが唯一の引数として渡されます。 これらの Proc オブジェクトはソケットの作成中に連続して実行されます。

警告

TLS コンテキスト フックはグローバルであり、アプリケーション内のすべての Mongo::Client インスタンスに影響します。

TLS コンテキスト フックの詳細については、 Rubyドライバー ドキュメントの「 SSLContext の変更 」を参照してください。

Mongoid は、 MongoDBとの間のメッセージの圧縮をサポートしています。 この機能はRubyドライバーによって提供され、次のサポートされているアルゴリズムを実装します。

  • Zstandard( 推奨 ):zstandard 圧縮を使用するには、 zstd-ruby ライブラリをインストールする必要があります。このコンプレッサーは、他のコンプレッサーと比較して、同じ CPU 消費で最も高い圧縮を生成します。

  • Snappy : 圧縮を使用するには、Snappysnappy ライブラリをインストールする必要があります。

  • zlib :zlib 圧縮を使用するには、zlib ライブラリをインストールする必要があります。

ワイヤプロトコル圧縮を使用するには、mongoid.ymlファイルでドライバー オプションを構成します。

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

コンプレッサーを明示的にリクエストしない場合、1 つ以上のコンプレッサーに必要な依存関係がインストールされていても、ドライバーは圧縮を使用しません。

ドライバーは、 MongoDBデプロイでサポートされている最初のコンプレッサーを指定した場合、最初のコンプレッサーを選択します。