Docs Menu

構成

Mongoid は、オプションとクライアントを指定する mongoid.ymlファイルを介してカスタム構成されます。 最も単純な構成は次のとおりです。これは、Mongoid が "localhost:27017" の MongoDB サーバーとやり取りし、"mongoid" という名前のデータベースを使用するように構成します。

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

構成ファイルの最上位キー(上記の例ではdevelopment )は、アプリケーションが実行されている環境名developmenttest 、またはproductionを示します。 上記の例では 3 つ目のレベルのキー default は、 mongoクライアント名を参照します。 ほとんどのアプリケーションはdefaultという名前の単一のクライアントを使用します。

Ruby on Rails を使用している場合は、次のコマンドを実行して Mongoid にデフォルトの構成ファイルを生成できます。

rails g mongoid:config

構成ファイルはconfig/mongoid.ymlに配置されます。

Ruby on Rails を使用していない場合は、上記の最小構成をコピーして、 config/mongoid.ymlとして保存できます。

Ruby on Rails を使用している場合、アプリケーションの読み込み時に、 Rails.envに保存されている現在の環境の Mongoid 構成が自動的に読み込まれます。

アプリケーションの ORM を Mongoid となるように構成するには、以下をapplication.rbに追加します。

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

Ruby on Rails を使用していない場合、Mongoid 構成は手動でロードする必要があります。 これは、次のように構成ファイル パスを引数としてMongoid.load!メソッドで実行できます。

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

Mongoid が環境名を自動的に検出するよう求めている場合、次のソースを順番に調べます。

  • Railsの最上位定数が定義されている場合、 Rails.envは 。

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

  • RACK_ENV 環境変数。

  • MONGOID_ENV 環境変数。

構成ファイルを使用せずに、Ruby で Mongoid を直接構成することもできます。 この構成スタイルは、環境の概念をサポートしていません。どの構成が提供されているかは、現在の環境に適用されますが、複数のクライアントの定義はサポートされています。

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

注意

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

次の注釈付きの例mongoid.ymlは、Mongoid の構成方法を示しています。

Mongoid は、クライアント構成を Ruby ドライバーに委任します。 ドライバー オプションの詳細については、 ドライバー のドキュメントを参照してください。

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://mongodb.com/ja-jp/docs/ruby-driver/current/reference/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. Please see the
# driver documentation linked above for details on how to configure
# authentication. Valid options are :aws, :gssapi, :mongodb_cr,
# :mongodb_x509, :plain, :scram and :scram256 (default on 3.0
# and higher servers is :scram, default on 2.6 servers is :plain)
auth_mech: :scram
# Specify the auth source, i.e. the database or other source which
# contains the user's login credentials. Allowed values for auth source
# depend on the authentication mechanism, as explained in the server documentation:
# https://mongodb.com/ja-jp/docs/manual/reference/connection-string/#mongodb-urioption-urioption.authSource
# If no auth source is specified, the default auth source as
# determined by the driver will be used. Please refer to:
# https://mongodb.com/ja-jp/docs/ruby-driver/current/reference/authentication/#auth-source
auth_source: admin
# Connect directly to and perform all operations on the specified
# server, bypassing replica set node discovery and monitoring.
# Exactly one host address must be specified. (default: false)
#direct_connection: true
# Deprecated. Force the driver to connect in a specific way instead
# of automatically discovering the deployment type and connecting
# accordingly. To connect directly to a replica set node bypassing
# node discovery and monitoring, use direct_connection: true instead
# of this option. Possible values: :direct, :replica_set, :sharded.
# (default: none)
#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
# How long to wait for a response for each operation sent to the
# server. This timeout should be set to a value larger than the
# processing time for the longest operation that will be executed
# by the application. Note that this is a client-side timeout;
# the server may continue executing an operation after the client
# aborts it with the SocketTimeout exception.
# (default: nil, meaning no timeout)
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:
# Application name that is printed to the MongoDB logs upon establishing
# a connection in server versions 3.4 or greater. Note that the name
# cannot exceed 128 bytes in length. It is also used as the database name
# if the database name is not explicitly defined. (default: nil)
app_name: MyApplicationName
# Type of executor for queries scheduled using ``load_async`` method.
#
# There are two possible values for this option:
#
# - :immediate - Queries will be immediately executed on a current thread.
# This is the default option.
# - :global_thread_pool - Queries will be executed asynchronously in
# background using a thread pool.
#async_query_executor: :immediate
# Mark belongs_to associations as required by default, so that saving a
# model with a missing belongs_to association will trigger a validation
# error. (default: true)
belongs_to_required_by_default: true
# (Deprecated) Maintain broken behavior of sum over empty result sets for backwards
# compatibility. When calculating a sum on a field with a null context,
# for example:
#
# Product.none.sum(:price)
#
# ... return field name (`:price') instead of 0.
#
# When calculating a sum via a database query with an empty result set,
# for example:
#
# Product.where(impossible_condition: true).sum(:price)
#
# ... return nil instead of 0.
# (default: false)
#broken_aggregables: true
# (Deprecated) Ignore aliased fields in embedded documents when performing pluck and
# distinct operations, for backwards compatibility.
# (default: false)
#broken_alias_handling: true
# (Deprecated) Maintain broken `and' method behavior that existed in Mongoid 7.3
# and earlier for backwards compatibility: in some situations, conditions
# already present in a Criteria object would be replaced by newer
# conditions when `and' method is used instead of the new conditions
# being added to the existing conditions. This would happen when using
# the same operator on the same field multiple times. For example:
#
# Band.where(id: 1).and({year: {'$in' => [2020]}}, {year: {'$in' => [2021]}}).where(id: 2)
#
# yields the following criteria:
#
# <Mongoid::Criteria
# selector: {"_id"=>1, "year"=>{"$in"=>[2020]}, "$and"=>[{"_id"=>2}]}
# options: {}
# class: Band
# embedded: false>
#
# This is obviously incorrect as the {"$in"=>[2021]} clause is lost.
# Notice that the clause is only lost when both clauses are added using
# the #and method.
# (default: false)
#broken_and: true
# (Deprecated) When exiting a nested `with_scope' block, set the current scope to
# nil instead of the parent scope for backwards compatibility.
# (default: false)
#broken_scoping: true
# (Deprecated) Maintain broken update behavior in some cases for backwards
# compatibility.
#
# In Mongoid 7.3 and earlier, when assigning a value to an embedded
# document, then setting it to nil, then assigning the original value
# to it again, the second update would not work and the value for the
# embedded document would remain nil. Take this case:
#
# canvas.palette = palette
# canvas.palette = nil
# canvas.palette = palette
#
# ... where canvas embeds_one palette.
#
# In Mongoid 7.3 and earlier, canvas.palette would be nil when we would
# expect it to be palette. Set this option to true to keep this behavior,
# set the option to false to perform the second update correctly.
# (default: false)
#broken_updates: true
# (Deprecated) Time objects in Ruby have nanosecond precision, whereas MongoDB server
# can only store times with millisecond precision. Set this option to
# true to truncate times to millisecond precision when performing
# queries on already loaded embedded associations (this is also called
# "embedded matching" and is done completely in Ruby), to obtain the
# same query results when performing time comparisons regardless of
# which documents are being queried. Setting this option to false will
# produce different results for queries on embedded associations that
# are already loaded into memory vs queries on unloaded associations and
# top-level models. (default: true)
#compare_time_by_ms: false
# Set the global discriminator key. (default: "_type")
discriminator_key: "_type"
# Raise an exception when a field is redefined. (default: false)
duplicate_fields_exception: false
# Defines how many asynchronous queries can be executed concurrently.
# This option should be set only if `async_query_executor` option is set
# to `:global_thread_pool`.
#global_executor_concurrency: nil
# 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
# Whether to join nested persistence contexts for atomic operations
# to parent contexts by default. (default: false)
join_contexts: false
# (Deprecated) When this flag is true, the attributes method on a document will return
# a BSON::Document when that document is retrieved from the database, and
# a Hash otherwise. When this flag is false, the attributes method will
# always return a Hash. (default: false)
#legacy_attributes: true
# (Deprecated) Maintain legacy behavior of pluck and distinct, which does not demongoize
# values on returning them. Setting this option to false will cause
# pluck and distinct to return demongoized values. Setting this option to
# false will also allow retrieving *_translations fields from pluck and
# distinct and will return embedded values themselves (i.e. without
# putting them in a hash).
# (default: false)
#legacy_pluck_distinct: true
# When this flag is false, a document will become read-only only once the
# #readonly! method is called, and an error will be raised on attempting
# to save or update such documents, instead of just on delete. When this
# flag is true, a document is only read-only if it has been projected
# using #only or #without, and read-only documents will not be
# deletable/destroyable, but will be savable/updatable.
# When this feature flag is turned on, the read-only state will be reset on
# reload, but when it is turned off, it won't be.
# (default: false)
#legacy_readonly: true
# (Deprecated) Maintain legacy behavior of === on Mongoid document classes, which
# returns true in a number of cases where Ruby's === implementation would
# return false. Note that the behavior of === on Mongoid document
# instances differs from both the behavior of === on document classes
# and from Ruby's behavior of === on simple object instances regardless
# of the value of this option.
# (default: false)
#legacy_triple_equals: true
# Set the Mongoid and Ruby driver log levels when Mongoid is not using
# Ruby on Rails logger instance. (default: :info)
log_level: :info
# When using the BigDecimal field type, store the value in the database
# as a BSON::Decimal128 instead of a string. (default: true)
#map_big_decimal_to_decimal128: true
# (Deprecated) Force ``BSON::ObjectId#as_json`` method to return the hash
# { "$oid" => id.to_s }. When this option is false, and bson-ruby 5
# is used, the return value will be the hexadecimal ObjectId string only.
# (default: false)
#object_id_as_json_oid: true
# (Deprecated) When chaining the same operators that use the same field, setting this
# feature flag to false will cause those operators to be combined using an
# and. Setting this feature flag to true will cause the later chained
# operators to overwrite the earlier ones. (default: false)
#overwrite_chained_operators: 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
# (Deprecated) Use ActiveSupport's time zone in time operations instead of
# the Ruby default time zone. See the time zone section below for
# further information. (default: true)
use_activesupport_time_zone: true
# Return stored times as UTC. See the time zone section below for
# further information. Most applications should not use this option.
# (default: false)
use_utc: false
# (Deprecated) In MongoDB 4.0 and earlier, set whether to create
# indexes in the background by default. (default: false)
background_indexing: false
# Configure driver-specific options. (optional)
driver_options:
# When this flag is turned off, inline options will be correctly
# propagated to Mongoid and Driver finder methods. When this flag is turned
# on those options will be ignored. For example, with this flag turned
# off, Band.all.limit(1).count will take the limit into account, while
# when this flag is turned on, that limit is ignored. The affected driver
# methods are: aggregate, count, count_documents, distinct, and
# estimated_document_count. The corresponding Mongoid methods are also
# affected. (default: false, driver version: 2.18.0+)
#broken_view_options: false
# Validates that there are no atomic operators (those that start with $)
# in the root of a replacement document, and that there are only atomic
# operators at the root of an update document. If this feature flag is on,
# an error will be raised on an invalid update or replacement document,
# if not, a warning will be output to the logs. This flag does not affect
# Mongoid as of 8.0, but will affect calls to driver update/replace
# methods. (default: false, driver version: 2.18.0+)
#validate_update_replace: false

Mongoid は、特定のバージョンのデフォルトへの構成オプションの設定をサポートしています。 これは、新しい Mongoid バージョンにアップグレードするのに役立ちます。 Mongoid のバージョンをアップグレードするときは、 Mongoid::Configに以下を設定する必要があります。

Mongoid.configure do |config|
config.load_defaults <OLD VERSION>
end

そのため、Mongoid の新しいバージョンにアップグレードすると、コードは Mongoid の前のバージョンの構成オプションで実行されます。 次に、新しいバージョンの機能フラグを 1 つずつ変更し、コードが引き続き期待どおりに動作することをテストできます。 新しい機能フラグをすべて考慮したら、 load_defaultsへの呼び出しが新しいバージョンで取得されるように変更され、変更された機能フラグをすべて削除できます。 たとえば、7.5 から 8.0 にアップグレードするとします。 これらの 2 つのバージョン間で、 legacy_attributesmap_big_decimal_to_decimal128の 2 つの機能フラグのみが追加されました。 Mongoid 8 にアップグレードする前に、次の行を追加できます。

Mongoid.configure do |config|
config.load_defaults 7.5
end

アップグレード後、これら 2 つの機能フラグはデフォルトで 7.5 機能( legacy_attributes: true, map_big_decimal_to_decimal128: false )になります。 ここで、これらの機能フラグを 1 つずつ設定し、8.0 の動作に戻すことができます。

Mongoid.configure do |config|
config.load_defaults 7.5
config.legacy_attributes = false
# config.map_big_decimal_to_decimal128 = true
end

これらは一度に 1 つずつ実行することをお勧めするため、2 番目のフラグはコメントアウトしています。 legacy_attributesフラグをオフにしてコードが期待どおりに動作することを確認したら、 map_big_decimal_to_decimal128設定のコメント解除が可能になります。 この機能も検証されたら、これらの行の両方を削除し、 load_defaultsは次のように置き換えられます。

Mongoid.configure do |config|
config.load_defaults 8.0
end

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

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

注意

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

注意

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

ロギングを構成する際は、Mongoid が MongoDB Ruby ドライバー上にモデルレイヤーを提供し、ドライバーが CRUD 操作を MongoDB 配置にディスパッチすることに注意してください。 そのため、Mongoid を使用するアプリケーションのログ出力の一部は Mongoid 自体から取得され、一部はドライバーから取得されます。

mongoクライアントはRubyドライバー クライアント インスタンスであるため、 mongoクライアントのロガーは Mongoid ロガーではなくRubyドライバー ロガーです。 つまり、次のようになります。

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

Mongoid が Ruby on Rails アプリケーションで使用されているかどうか、および Mongoid ドライバーと Ruby ドライバーの両方がどのように構成されているかに応じて、同じロガー インスタンスまたは異なる インスタンスを使用する場合があり、構成が異なる場合があります。

Ruby on Rails アプリケーションで使用する場合、Mongoid はデフォルトで Rails からロガーとログ レベルを継承し、ドライバーのロガーを同じロガー インスタンスに設定します。

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

ログレベルを変更するには、 標準の Rails 構成 を使用します 。環境構成ファイルの 1 つに以下を配置します( config/environments/production.rbなど)。

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

注意

Mongoid が Rails アプリケーションで動作する場合、 log_level Mongoid 構成オプションは使用されません。この場合、Mongoid は Rails のログレベルを継承するためです。

Mongoid ロガーまたはドライバー ロガーのいずれかを Rails ロガーとは異なる方法で構成するには、次のように初期化子を使用します。

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

注意

Ruby 標準ライブラリLoggerには現在、ロガーが使用しているログデバイス( IOオブジェクト)を返すためのプロビジョニングはありません。 たとえば、Mongoid や Ruby ドライバーのログを標準の Rails ログファイル(例: log/development.log )ただし、標準の Rails ロガー( Rails.logger )とは異なるレベルでは、ファイルを個別に開き、結果のIOオブジェクトをLoggerコンストラクターに渡す必要があります。

注意

デフォルトでは、Mongoid は自分のロガーとドライバーのロガーを Rails ロガーと同じインスタンスに設定するため、 インスタンスのいずれかを変更すると、それらすべてに影響します。 たとえば、次の変更では、上記の説明のように、アプリケーションがMongo::Logger.loggerに個別のLoggerインスタンスを割り当てていない限り、3 つのロガーすべてのログ レベルが変更されます。

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

Ruby on Rails アプリケーションにロードされていない場合、Mongoid はlog_level最上位構成オプションを尊重します。 これは、次のように構成ファイルで指定できます。

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

... または Mongoid インラインで構成する場合は、次のようにします。

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

Mongoid 7.1 以降のデフォルトのログ先は標準エラーです。 Mongoid 7.0 以前のデフォルトのログ先は標準出力です。 ログの保存先を変更するには、次のように新しいロガー インスタンスを作成します。

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

Ruby ドライバーのログ レベルまたは宛先変更先を変更するには:

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

ドライバー ロガーを Mongoid ロガーと同じものに設定するには、次の手順に従います。

Mongo::Logger.logger = Mongoid.logger

注意

Mongoid は、スタンドアロン モードで実行中にドライバーのロガーを変更しません。

Ruby は、標準ライブラリで限定的なタイム ゾーンをサポートしています。 ActiveSupport (Mongoid が依存するもの)は、より包括的なタイムゾーンのサポートを提供します。 重要になっているのは、Ruby と ActiveSupport は異なるデフォルトのタイムゾーンで構成されている場合があることです。

Ruby のタイム ゾーンの完全な処理は、このチュートリアルの範囲外ですが、正しいタイム ゾーンの処理を実現する最も簡単で確実な方法は次のとおりです。

  1. オペレーティング システムのタイム ゾーンを UTC に設定します。 たとえば、Linux の場合は次のようになります。

cp /usr/share/zoneinfo/UTC /etc/localtime
  1. ActiveSupport のタイムゾーンを UTC に設定します。

# If using Rails, in application.rb:
class Application < Rails::Application
config.time_zone = 'UTC'
end
# If not using Rails:
Time.zone = 'UTC'
  1. 保存し、常に UTC で永続化します。 すべての計算は UTC の回数で実行します。

  2. ローカル時間でユーザー入力を操作する場合は、そのようなユーザー入力を可能な限りすぐに UTC 時間に変換し、その後 UTC 時間で操作します。

  3. 時刻をレンダリングしたり、その他で表示する場合は、実際にレンダリングするときに、すべての計算を実行した後、ローカル時間に変換します。

  4. 日時(たとえば、特定の日の開始時刻または終了時刻)の変換はエラーの一般的な原因であり、 このような変換は通常、日付が解釈されるタイムゾーンを明示的に指定しながら実行する必要があります。

Mongoid を使用するアプリケーションでは、通常、上記のように ActiveSupport のタイムゾーンを構成し、Time.zone ではなくTime を使用して(たとえば、Time.zone.now ではなくTime.now )、ActiveSupport タイムゾーン メカニズムを呼び出す必要があります。これは、開発環境で一般的なように、システム タイム ゾーンが UTC でない場合にも正しい結果を得るのに役立ちます。

MongoDB は、タイムゾーン情報なしですべての時間を UTC で保存することに注意してください。

Mongoid には、次のタイムゾーン関連の構成オプションがあります。

  • use_activesupport_time_zone: このオプションは非推奨であり、Mongoid 9.0 では常に true として動作します。

    true の場合(デフォルト)、 ActiveSupport::TimeWithZoneを使用して 時間で動作するようにします。 Time型のフィールドの値はActiveSupport::TimeWithZoneのインスタンスとして返されます。 タイムゾーン情報なしで時間を解析する場合(string や配列を時間単位で mongoized する場合など)、 は ActiveSupport のタイムゾーンで時間が指定されていると想定します。 これがデフォルトです。

    false の場合、Ruby 標準ライブラリのTimeクラスを使用して 時間で動作することを優先します。 Time型のフィールドの値はTimeインスタンスとして返されます。 タイムゾーン情報なしで時間を解析する場合、 は Ruby タイムゾーンで指定されている時刻を想定します。

    の設定は、それぞれの値に use_activesupport_time_zoneクラスと クラスを使用するDate または のフィールドには影響しないことに注意してください。DateTimeDateDateTime

    また、Mongoid は、Time ActiveSupport::TimeWithZoneの設定に関係なく、必要に応じて クラスとuse_activesupport_time_zone クラスの両方を内部で使用することにも注意してください。

  • use_utc: true の場合、MongoDB に保存されている時刻は UTC で返されます。 false の場合、MongoDB に保存されている時間はローカル時間( use_activesupport_time_zone設定の値に基づき、それぞれ Ruby のデフォルト タイムゾーンまたは ActiveSupport タイムゾーンにあるTimeまたはActiveSupport::TimeWithZoneのインスタンスとして返されます。 デフォルトは false です。

    use_utcの設定は、時刻の解析方法には影響しません。解析は、解析される入力にタイムゾーン情報が含まれていない場合、常にローカル タイムで行われます。 日付を UTC で解析するには、システム/Ruby または ActiveSupport タイム ゾーンを UTC に設定します(前述のように、3 つすべてを UTC に設定すると、ヘッドルームが最も少なくなります)。

    use_activesupport_time_zoneを true に設定し、 Time.zoneを UTC に設定する(および時間に関連するすべての操作に ActiveSupport 時間メカニズムを使用する)ことは、 use_utcを true に設定するよりも推奨されます。

use_activesupport_time_zoneuse_utcのオプションは、使用可能な場合、タイムゾーン情報をスローしないことに注意してください。 たとえば、Time インスタンスには関連付けられたタイムゾーンがあり、 use_activesupport_time_zoneが true になっている場合は、ActiveSupport の構成されたタイムゾーンと異なる場合でも、このタイムゾーンが使用されます。

特定の暗号を有効または無効にするなど、アプリケーションで TLS オプションをさらに構成することが必要な場合があります。

これは、Ruby ドライバーに TLS コンテキスト フックを設定することで実行できます。TLS コンテキスト フックは、ソケットで使用されるユーザー提供の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オブジェクトです。

TLS コンテキスト フックを設定するには、 Proc``s to the ``Mongo.tls_context_hooks配列を追加します。 これは初期化で実行できます。 以下の例では、「AES256-SHA」暗号のみを有効にするフックを追加しています。

Mongo.tls_context_hooks.push(
Proc.new { |context|
context.ciphers = ["AES256-SHA"]
}
)
# Only the AES256-SHA cipher will be enabled from this point forward

Proc内のすべてのMongo.tls_context_hooks OpenSSL::SSL::SSLContextには、単一の引数として オブジェクトが渡されます。これらのプロシージャは、ソケットの作成中に順番に実行されます。

警告

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

TLS コンテキスト フック(割り当てと削除のベストプラクティスを含む)の詳細については、 Ruby ドライバーのドキュメントを参照してください。

構成ファイルをロードする際、Mongoid は次の例に示すように、クライアント側の暗号化のスキーマ マップでkeyIdを指定するために使用されるBSON::Binaryインスタンスをファイルに含めることを許可します。

development:
clients:
default:
database: blog_development
hosts: [localhost:27017]
options:
auto_encryption_options:
key_vault_namespace: 'keyvault.datakeys'
kms_providers:
local:
key: "z7iYiYKLuYymEWtk4kfny1ESBwwFdA58qMqff96A8ghiOcIK75lJGPUIocku8LOFjQuEgeIP4xlln3s7r93FV9J5sAE7zg8U"
schema_map:
blog_development.comments:
properties:
message:
encrypt:
keyId:
- !ruby/object:BSON::Binary
data: !binary |-
R/AgNcxASFiiJWKXqWGo5w==
type: :uuid
bsonType: "string"
algorithm: "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic"
bsonType: "object"

Pume、Unicode、Password などのフォーク Web サーバーで Mongoid を使用する場合は、フォークの前に親プロセスの Mongoid モデルに対して操作を実行しないことをお勧めします。

プロセスがフォークすると、Ruby スレッドは子プロセスに転送されず、Ruby ドライバー クライアント オブジェクトはバックグラウンド監視を失います。 アプリケーションは通常、配置状態が変化するまで正常に動作しているように見えますが、その時点でアプリケーションは MongoDB 操作を実行するときにNoServerAvailable例外を取得し始める可能性があります。

親プロセスが MongoDB database に対して操作を実行する必要がある場合は、フォークした後にワーカー内のすべてのクライアントをリセットします。 その方法は、使用されているウェブ サーバーによって異なります。

子プロセスがフォークされた後に親プロセスが MongoDB database に対して操作を実行する必要がない場合は、子をフォークする前に親のクライアントを閉じます。 親プロセスがmongoクライアントに対して操作を実行し、それが閉じられない場合、親プロセスはクラスター内の接続スロットを消費し続け、親が有効である限りクラスターを監視し続けます。

注意

ここで説明されている閉じ/再接続のパターンは、Ruby ドライバー バージョン 2.6.2 以降で使用する必要があります。 以前のドライバー バージョンでは、再接続時に監視スレッドが再作成されませんでした。

on_worker_bootワーカー内のクライアントを再接続するには フックを使用し、親プロセス内のクライアントを閉じるにはbefore_fork フックを使用します( Pume ドキュメント ):

on_worker_boot do
if defined?(Mongoid)
Mongoid::Clients.clients.each do |name, client|
client.close
client.reconnect
end
else
raise "Mongoid is not loaded. You may have forgotten to enable app preloading."
end
end
before_fork do
if defined?(Mongoid)
Mongoid.disconnect_clients
end
end

after_forkフックを使用してワーカー内のクライアントを再接続し、before_fork フックを使用して親プロセス内のクライアントを閉じます( Unicode ドキュメント ):

after_fork do |server, worker|
if defined?(Mongoid)
Mongoid::Clients.clients.each do |name, client|
client.close
client.reconnect
end
else
raise "Mongoid is not loaded. You may have forgotten to enable app preloading."
end
end
before_fork do |server, worker|
if defined?(Mongoid)
Mongoid.disconnect_clients
end
end

starting_worker_processフックを使用してワーカー内のクライアントを再接続します( 乗用ドキュメント )。ペインには、ワーカーがフォークされる前に親プロセスで呼び出されるフックが存在するようには表示されません。

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

注意

Ruby ドライバー バージョン2.15以降で使用する場合、Mongoid の クエリ キャッシュ ミドルウェアはドライバーの クエリキャッシュ ミドルウェア に委任します。

Mongoid は、各ウェブ リクエストの実行中にクエリ キャッシュを有効にする Rack ミドルウェアを提供します。 以下は、Ruby on Rails アプリケーションでクエリ キャッシュ ミドルウェアを有効にする方法の例です。

# config/application.rb
# Add Mongoid::QueryCache::Middleware at the bottom of the middleware stack
# or before other middleware that queries MongoDB.
config.middleware.use Mongoid::QueryCache::Middleware

Rails on Rack ガイド を参照してください Rails アプリケーションで Rack ミドルウェアを使用する方法の詳細については、 を参照してください。

ドライバーのデフォルト構成は本番環境の配置に適しています。 開発では、開発者エクスペリエンスを向上させるために一部の設定を調整することができます。

  • :server_selection_timeout: MongoDB サーバーがローカルで実行され、手動で起動する場合は、これを低い値(例: 1 )に設定します。 サーバー選択タイムアウトが短いと、サーバーが実行されていない場合にドライバーがすぐに失敗します。

推奨される開発構成の例は以下のとおりです。

development:
clients:
default:
database: mongoid
hosts:
- localhost:27017
options:
server_selection_timeout: 1