次の新機能をご覧ください。
リリースと詳細なリリースノートの一覧を表示するには、 Githubの Mongoid リリース を参照してください。
9.1の新機能
9.1 リリースには、次の新機能、改善点、修正が含まれています。
Adds the
Criteria#rawmethod that allows you to retrieve results as raw hashes. To learn more, see the Return Raw Data section of the Modify Query Results guide.cache_keyの動作を変更することで、cache_versionが nil 以外の値を返す場合にタイムスタンプが埋め込まれないようにし、キャッシュ機能を向上させます。代わりに、キー チャーンを減らすために、タイムスタンプがエントリのバージョンとして使用されます。この変更により、
Mongoid::Documentモジュールにcache_versionメソッドも追加されます。このバージョンで導入されたキャッシュキーの形式によってアプリケーションで問題が発生する場合は、cache_versionメソッドをnilとして定義することで元の形式に戻すことができます。module Mongoid module Document def cache_version = nil end end Updates the
serializable_hashmethod to include a newMongoid::Config.serializable_hash_with_legacy_onlyoption, which defaults totrue. When this option is enabled, the Ruby driver uses the pre-existing legacyserializable_hashbehavior. This behavior returns all keys when you pass an empty array for the:onlyoption. Mongoid will deprecate this legacy behavior in v10.0.同時操作のデフォルトの分離レベルを構成できる
Mongoid.isolation_levelプロパティを追加します。デフォルトの分離レベルは:railsで、ActiveSupport::IsolatedExecutionStateから分離レベルを継承します。また、既存のスレッドローカル分離レベル機能から:threadオプションを指定したり、親ファイルから内部状態を継承するには、:fiberオプションを指定したりすることもできます。any?、one?、many?の列挙可能メソッドをCriteriaクラスに追加し、クラスレベルでscopedに委任します。これらのメソッドは、ドキュメントをメモリにロードするのではなく、 MongoDBcount関数を使用するため、ドキュメントがまだ取得されていない場合のパフォーマンスが向上します。次の例では、これらのメソッドの使用方法を示しています。User.any? # Returns true if any user documents exist User.one? # Returns true if exactly one user document exists in the criteria User.many? # Returns true if more than one user document exists in the criteria Adds the
Criteria#to_mqlmethod, which returns the MongoDB Query Language (MQL) representation of a query. Use this method to inspect the queries that Mongoid generates. The following example returns the MQL for aPersonquery:Person.where(age: { '$gt' => 18 }).to_mql Adds the
Criteria#eager_loadmethod for loading associations using an aggregation pipeline. Unlikeincludes,eager_loadissues a single query to the database. This method performs better onhas_manyandhas_and_belongs_to_manyassociations and on queries that join multiplebelongs_toorhas_oneassociations. If you useeager_loadon an embedded association, Mongoid falls back toincludes. The following example eager-loads theemployerandpartnerassociations for active persons:Person.where(active: true).eager_load(:employer, :partner) Adds MongoDB Vector Search support. Define a MongoDB Vector Search index by using the
vector_fieldmacro or thevector_search_indexmethod, then callvector_searchto query for semantically similar documents. To learn more, see the MongoDB Vector Search overview. The following example defines a MongoDB Vector Search index on anArticlemodel and queries for similar documents:class Article include Mongoid::Document vector_field :embedding, dimensions: 1536 end articles = Article.vector_search(query_vector, limit: 5) Adds the
auto_embed_fieldmacro, which enables auto-embedding in MongoDB Vector Search support. Mongoid uses the configured embedding model to automatically index the field. To learn more, see MongoDB Vector Search Quick Start in the MongoDB Vector Search documentation. The following example defines an auto-embedding field and queries for similar articles:class Article include Mongoid::Document auto_embed_field :body end articles = Article.auto_embed_search('machine learning', limit: 5) Adds support for specifying the associated document type when calling
build_<association>orcreate_<association>onembeds_one,has_one, andbelongs_toassociations. The following example builds aHeadlessRunnerfor aJobassociation:job = Job.create job.build_runner({ name: 'My Runner' }, HeadlessRunner) Adds the
Mongoid.allow_short_circuit_queriesconfiguration option. When set totrue, a top-level$incondition with an empty array returns an empty result without querying the database. This option defaults tofalse. The following example enables the option:Mongoid.allow_short_circuit_queries = true Document.in(ids: []) # Returns [], no database query issued Updates duplicate index declaration behavior. Mongoid now ignores index declarations that differ only in their options, including the index name. To allow near-identical index declarations to be sent to the server, set
Mongoid.allow_duplicate_index_declarations = true.Deprecates the
Criteria#max_scanmethod.Changes the default of
Mongoid::Config.allow_reparenting_via_nested_attributestofalse. Set this option totrueto restore the earlier behavior. This option will be removed in Mongoid v10.Changes the default of
Mongoid.autosave_saves_unchanged_documentstofalse. Set this option totrueto restore the earlier behavior. This option will be removed in Mongoid v10.
9.0.11の新機能
9.0.11 リリースには、次の新機能が含まれています。
allow_reparenting_via_nested_attributes 構成
Mongoid v9.0.11 では Mongoid::Config.allow_reparenting_via_nested_attributes 構成オプションが導入されています。このオプションは、ネストされた属性を通じて依存している has_many レコードを再親化できるかどうかを制御します。
オプションのデフォルトは true で、レガシー動作は維持されます。ネストされた属性による再親化を防ぐには、このオプションを false に設定します。
Mongoid::Config.allow_reparenting_via_nested_attributes = false
Mongoid v9.1 では、このオプションはデフォルトで false になります。オプションは Mongoid v10 で削除されます。
変更されていないサブツリーの自動保存動作
Mongoid v9.0.11 では Mongoid.autosave_saves_unchanged_documents 構成オプションが導入されています。このオプションは、サブツリー内のドキュメントが autosave: true になっている場合に、Mongoid が 関連付けサブツリー 内のすべてのドキュメントを自動保存するかどうかを制御します。
Mongoid の以前のバージョンでは、autosave: true との関連付けにより、ドキュメントが変更されたかどうかにかかわらず、Mongoid はすべての子ドキュメントで #save を呼び出し、対応するすべての after_save フックを再帰的に呼び出します。
オプションのデフォルトは true で、レガシー動作は維持されます。変更されたドキュメントを含むサブツリーのみを自動保存するには、このオプションを false に設定します。
Mongoid.autosave_saves_unchanged_documents = false
Mongoid v9.1 では、このオプションはデフォルトで false になります。オプションは Mongoid v10 で削除されます。
Ruby 4.0 のサポート
Mongoid v9.0.11 はRuby 4.0 の公式サポートを追加します。
9.0.7の新機能
警告
重大な変更
9.0.7 リリースには重大な変更が含まれています。
9.0.7 リリースには次の変更が含まれています。
Mongoid の前のバージョンでは、子が変更されていない場合、親の状態に依存する子コールバックが呼び出されなくなるバグが修正されていました。修正によってパフォーマンスの低下が導入されたため、このパッチ バージョンは以前の機能を復元します。子コールバックは、子自体が変更された場合にのみ呼び出されるようになりました。これにより、変更されていない子で呼び出されるコールバックに依存するアプリの重大な変更が導入されます(例、子コールバックが親の状態が変更された場合に依存する場合)。
次のコードサンプルは、親の変更に応じて子コールバックを呼び出す方法を示しています。
class Parent include Mongoid::Document has_many :children after_save { children.each(&:parent_changed_callback) } end class Child include Mongoid::Document belongs_to :parent def parent_changed_callback # ... end end
9.0の新機能
9.0 リリースには、次の新機能、改善点、修正が含まれています。
Railsmdb
Mongoid v9.0 のリリースに加えて、 Rails アプリケーションの作成、更新、管理、メンテナンス用コマンドライン ユーティリティ、railsmdb が一般提供されています。
railsmdb Ruby on Rails 開発者がすでに知っている一般的なジェネレーターを使用して、コマンドラインから MongoDB を操作するのを容易にします。
たとえば、 railsmdbを使用して新しい Mongoid モデルのスタブを生成できます。
bin/railsmdb generate model person
これにより、 app/models/person.rbに新しいモデルが作成されます。
class Person include Mongoid::Document include Mongoid::Timestamp end
モデルのフィールドを指定できます。
bin/railsmdb generate model person name:string birth:date
class Person include Mongoid::Document include Mongoid::Timestamp field :name, type: String field :birth, type: Date end
--parentオプションを渡すことで、ジェネレーターに新しいモデルを別のサブクラスにするように指示できます。
bin/railsmdb generate model student --parent=person
class Student < Person include Mongoid::Timestamp end
モデル名から推論できるとは別のコレクションにモデルを保存する必要がある場合は、--collection を指定できます。
bin/railsmdb generate model course --collection=classes
class Course include Mongoid::Document include Mongoid::Timestamp store_in collection: 'classes' end
詳細については、 Githubのmongoid- Railsmdbリポジトリを参照してください。
Ruby2.6 および JRuby のサポートの削除9.3
Mongoid v9.0 Ruby 2.7 以降、または JRuby 9.4 が必要です。 以前のバージョンのRubyおよび JRuby はサポートされていません。
Rails 5 のサポートの削除
Mongoid v9.0 Rails 6.0 以上が必要です。 以前の Rails バージョンはサポートされていません。
非推奨クラスの削除 Mongoid::Errors::InvalidStorageParent
非推奨クラスMongoid::Errors::InvalidStorageParentが削除されました。
around_* Callbacks for Embedded Documents are Ignored by Default
Mongoid v8.x and older allows users to define around_* callbacks for embedded documents. Starting in v9.0, by default these callbacks are ignored and will not be executed. A warning will be printed to the console if such callbacks are defined.
If you want to restore the old behavior, you can set Mongoid.around_callbacks_for_embeds to true in your application.
注意
埋め込みドキュメントで around_* コールバックを有効にすることは推奨されません。埋め込みドキュメントが多い場合に SystemStackError の例外が発生する可能性があるためです。詳細については、 MONGOID-5658 を参照してください。
for_js メソッドは非推奨
for_js メソッドは非推奨であり、Mongoid v10.0 で削除される予定です。
非推奨オプションの削除
重大な変更: Mongoid v で次の構成オプションが削除されます。9.0アプリからこれらへのすべての参照を削除したことを確認してください。 アップグレードする前に config.load_defaults 8.1 を使用していた場合、動作の変更は発生しません。 各オプションの意味については、以前のリリースノートを参照してください。
:use_activesupport_time_zone:broken_aggregables:broken_alias_handling:broken_and:broken_scoping:broken_updates:compare_time_by_ms:legacy_attributes:legacy_pluck_distinct:legacy_triple_equals:object_id_as_json_oid:overwrite_chained_operators
さらに、v7.5 以前のバージョンの config.load_defaults のサポートは削除されました(少なくとも v8.0 のバージョンを使用する必要があります)。
非推奨機能の削除
重大な変更:次の非推奨機能が削除されました。
Mongoid::QueryCacheモジュールが削除されました。 1 の 1 の使用をMongo::QueryCacheに置き換えてください。 メソッドMongoid::QueryCache#clear_cacheはMongo::QueryCache#clearに置き換える必要があります。 他のすべてのメソッドとサブモジュールは同じ名前です。Object#blank_criteria?メソッドは削除されました(以前は非推奨)。Document#as_json :compactオプションが削除されます。 代わりに、返されたHashオブジェクトで`#compactを呼び出してください。非推奨クラス
Mongoid::Errors::InvalidStorageParentが削除されました。
スレッド ローカル変数の取得と設定
バージョン9.0.3の新機能。
Mongoid::Threaded.get メソッドと Mongoid::Threaded.set メソッドを使用して、スレッド ローカル変数をクエリおよび変更できます。これらのメソッドをいつ使用するかについては、 コールバックガイドの「 スレッド ローカル変数 」セクションを参照してください。
インデックス検証構成
バージョン9.0.7の新機能。
Mongoid.allow_duplicate_index_declarations 構成オプションを使用して、インデックス検証をサーバーに送信できます。重複インデックスが宣言されている場合、サーバーはエラーを発生させます。詳細については、 アプリケーション構成ガイドの 「構成オプション」セクション を参照してください。
touch 変更された状態をクリアするメソッド
Mongoid v8.x 以前では、touch メソッドは変更された状態のモデルを残ります。
# v8.x behaviour band = Band.create! band.touch band.changed? # => true band.changes # => {"updated_at"=>[2023-01-30 13:12:57.477191135 UTC, 2023-01-30 13:13:11.482975646 UTC]}
v9.0 以降、 Mongoid は、touch メソッドを使用して変更された状態を正しくクリアするようになりました。
# v9.0 behavior band = Band.create! band.touch band.changed? # => false band.changes # => {}
Rails コンソールのサンドボックス モード
Mongoid が Rails コンソール サンドボックスモードをサポートするようになりました。 Rails コンソールが --sandbox フラグで起動した場合、Mongoid はコンソールを開く前に :defaultクライアントでトランザクションを開始します。 このトランザクションはコミットされません。 したがって、:defaultクライアントを使用してコンソールで実行されたすべてのコマンドは、データベースに保持されません。
注意
デフォルト以外のクライアントを使用してサンドボックス モードでコマンドを実行すると、これらの変更は通常どおり保持されます。
新しいトランザクション API
Mongoid 9.0 は、ActiveRecord に触発された新しいトランザクションAPIを導入しています。
Band.transaction do Band.create(title: 'Led Zeppelin') end band = Band.create(title: 'Deep Purple') band.transaction do band.active = false band.save! end
詳細については、「 トランザクションとセッション のガイド 」を参照してください。
埋め込みドキュメントでは常に親永続コンテキストが使用されます
Mongoid v8.x 以前では、ユーザーは埋め込みドキュメントの永続性コンテキストを指定できます(store_in マイクロを使用)。 Mongoid v9.0 では 埋め込みドキュメントでは、これらの設定は無視されます。 埋め込みドキュメントは、常に親の永続化コンテキストを使用するようになりました。
クエリに未加工値を渡すためのサポート
クエリを実行する際に、Mongoid::RawValueラッパークラスを使用して Mongoid の型変換ロジックをスキップできるようになりました。 これは、データベース内のレガシーデータがフィールド定義とは異なるタイプである場合に便利です。
class Person include Mongoid::Document field :age, type: Integer end # Query for the string "42", not the integer 42 Person.where(age: Mongoid::RawValue("42"))
クエリプロジェクションから省略されたフィールドにアクセスするときに AttributeNotLoaded エラーが発生する
インスタンスがロードされたときにonlyまたはwithoutクエリプロジェクション メソッドによって除外されたモデル インスタンスのフィールドにアクセスしようとすると、Mongoid はMongoid::Errors::AttributeNotLoadedエラーを発生させるようになります。
Band.only(:name).first.label #=> raises Mongoid::Errors::AttributeNotLoaded Band.without(:label).first.label = 'Sub Pop Records' #=> raises Mongoid::Errors::AttributeNotLoaded
Mongoid の以前のバージョンでは、同じ条件でActiveModel::MissingAttributeErrorが発生していました。 このクラスの Mongoid 固有の使用状況をコードで確認し、それをMongoid::Errors::AttributeNotLoadedに変更してください。 さらに、 AttributeNotLoadedはMongoid::Errors::MongoidErrorを継承している間に、 ActiveModel::MissingAttributeErrorは継承していないことにも注意してください。
構成されたタイムゾーンを使用してクエリで Date を Time にタイプキャストする
Date 値を使用して Time フィールドをクエリする場合、Mongoid はTime.zoneを正しく考慮して型変換を実行するようになりました。
class Magazine include Mongoid::Document field :published_at, type: Time end Time.zone = 'Asia/Tokyo' Magazine.gte(published_at: Date.parse('2022-09-26')) #=> will return all results on or after Sept 26th, 2022 # at 0:00 in Asia/Tokyo time zone.
Mongoid の以前のバージョンでは、上記のコードでは Time.zone(削除された :use_activesupport_time_zone 設定に関係なく)を無視し、常にシステム タイムゾーンを使用して型変換を実行していました。
以前の Mongoid バージョンでは、永続化操作中に Date を Time にタイプキャストする際に、タイムゾーン がすでに正しく使用されていることに注意してください。
touch 埋め込みドキュメントのメソッドが touch: false オプションを正しく取り扱う
embedded_in関係にtouch: falseオプションが設定されている場合、埋め込まれた子ドキュメントでtouchメソッドを呼び出しても、その親ドキュメントでtouchは呼び出されません。
class Address include Mongoid::Document include Mongoid::Timestamps embedded_in :mall, touch: false end class Mall include Mongoid::Document include Mongoid::Timestamps embeds_many :addresses end mall = Mall.create! address = mall.addresses.create! address.touch #=> updates address.updated_at but not mall.updated_at
さらに、 touchメソッドは、ネストされた埋め込みドキュメントを複数レベルで使用する場合でも、親ドキュメントごとに 1 つの永続化操作を実行するように最適化されています。
embedded_in 関連付けのデフォルト: touch: true
埋め込まれたサブドキュメントを更新すると、関係で明示的に touch: false を設定しない限り、自動的に親にアクセスするようになりました。
class Address include Mongoid::Document include Mongoid::Timestamps embedded_in :mall, touch: false end
その他のすべての関連付けでは、デフォルトはtouch: falseのままになります。
upsert の :replace オプションのデフォルトを反転
Mongoid v8.1 upsert メソッドに :replace オプションを追加しました。 このオプションは、既存のドキュメントを更新または置換するかどうかを指定するために使用されました。
Mongoid v9.0 は、このフラグのデフォルトを true から false に切り替えます。 つまり、デフォルトでは 、Mongoid v9.0 は既存のドキュメントを更新し、それを置き換えません。
強制される _id フィールドの不変性
Mongoid v9.0 より前は、 _idフィールドをミューテーションすると、ドキュメントが最上位か埋め込みか、および更新の実行方法に応じて動作に一貫性がありませんでした。 v9.0 では、 _idフィールドを変更すると、ドキュメントが以前に保存されていた場合、ドキュメントが保存されたときに例外が発生するようになりました。
Mongoid9.0 には新しい機能フラグimmutable_ids も導入され、デフォルトはtrue になります。
Mongoid::Config.immutable_ids = true
false に設定すると、古い、一貫性のない動作が復元されます。
インデックス オプションでのフィールド エイリアスのサポート
indexマイクロの次のオプションでエイリアス フィールド名を使用するためのサポートが追加されました。 partial_filter_expression 、 weights 、 wildcard_projection 。
class Person include Mongoid::Document field :a, as: :age index({ age: 1 }, { partial_filter_expression: { age: { '$gte' => 20 } }) end
注意
partial_filter_expressionなどのインデックス オプション内のフィールド名エイリアスの展開は、MongoDB サーバー6.0の動作に従って実行されます。 将来のサーバー バージョンでは、これらのオプションの解釈方法が変更される可能性があり、Mongoid の機能はそのような変更をサポートしない可能性があります。
BSON 5 フィールドと BSON::Decimal128 フィールド
BSON 4 またはそれ以前のバージョンが存在する場合、BSON::Decimal128 として宣言されたフィールドはBSON::Decimal128 値を返します。 ただし、 BSON 5 が存在する場合、BSON::Decimal128 として宣言されたフィールドはいずれもデフォルトで BigDecimal 値を返します。
class Model include Mongoid::Document field :decimal_field, type: BSON::Decimal128 end # under BSON <= 4 Model.first.decimal_field.class #=> BSON::Decimal128 # under BSON >= 5 Model.first.decimal_field.class #=> BigDecimal
BSON 5 でリテラルの BSON::Decimal128 値が必要な場合は、Mongoid にリテラル BSON::Decimal128 フィールドを許可するように指示できます。
Model.first.decimal_field.class #=> BigDecimal Mongoid.allow_bson5_decimal128 = true Model.first.decimal_field.class #=> BSON::Decimal128
注意
allow_bson5_decimal128オプションは BSON 5以降でのみ効果があります。 BSON 4以前は 設定を完全に無視します。
MongoDB Atlasの検索インデックス管理
MongoDB Atlasに接続すると、Mongoid は検索インデックスの作成と削除をサポートするようになりました。 Mongoid::SearchIndexable API を使用して、プログラムでこれを実行できます。
class SearchablePerson include Mongoid::Document search_index { ... } # define the search index here end # create the declared search indexes; this returns immediately, but the # search indexes may take several minutes before they are available. SearchablePerson.create_search_indexes # query the available search indexes SearchablePerson.search_indexes.each do |index| # ... end # remove all search indexes from the model's collection SearchablePerson.remove_search_indexes
MongoDB Atlas に接続していない場合、検索インデックスの定義は無視されます。 検索インデックスを作成、列挙、または削除しようとすると、エラーが発生します。
便宜上、使用可能な レイテンシ タスク も利用できます。
# create search indexes for all models; waits for indexes to be created # and shows progress on the terminal. $ rake mongoid:db:create_search_indexes # as above, but returns immediately and lets the indexes be created in the # background $ rake WAIT_FOR_SEARCH_INDEXES=0 mongoid:db:create_search_indexes # removes search indexes from all models $ rake mongoid:db:remove_search_indexes
の削除 Time.configured
Time.configured は、構成されたタイムゾーンをラップする時間オブジェクト、または標準の Ruby Timeクラスのいずれかを返しました。 これにより、タイム ゾーンが設定されていない場合でも、時間値をクエリできます。
Mongoid は、時間値を使用して何もする場合(ドキュメントでタイムスタンプを使用するなど)、タイムゾーンを設定する必要を持つようになりました。 Time.configuredの使用はすべてTime.zoneに置き換える必要があります。
# before: puts Time.configured.now # after: puts Time.zone.now # or, better for finding the current Time specifically: puts Time.current
タイムゾーンを設定しないと、 nil値に関連するコードにエラーが表示されます。 Rails を使用している場合、デフォルトのタイムゾーンはすでに UTC に設定されています。 Rails を使用していない場合は、次のようにプログラムの開始にタイムゾーンを設定できます。
Time.zone = 'UTC'
これにより、タイム ゾーンは UTC に設定されます。 次のコマンドを実行すると、使用可能なすべてのタイム ゾーン名を表示できます。
$ ruby -ractive_support/values/time_zone \ -e 'puts ActiveSupport::TimeZone::MAPPING.keys'
レコードは作成の永続性コンテキストを呼び出す
次のコードを考えてみましょう。
record = Model.with(collection: 'other_collection') { Model.first } record.update(field: 'value')
Mongoid v9.0 より前では、ストレージオプション(モデルの代替コレクションの指定)がレコードに保存されないため、上記のコードは暗黙的に更新を実行できません。 したがって、レコードはother_collection から読み込まれますが、更新されると、 は モデルのデフォルトコレクション内のドキュメントを検索して更新します。 これを機能させるには、アップデートごとにコレクションを明示的に指定する必要がありました。
Mongoid v9.0 以降、 明示的なストレージオプションの下で作成またはロードされたレコードは、それらのオプション( 名前付きクライアント、別のデータベース、または別のコレクションなど)を記憶します。
レガシー(v9.0 以前)が必要な場合 動作する場合は、次のフラグで有効にできます。
Mongoid.legacy_persistence_context_behavior = true
このフラグは、Mongoid v9.0 ではデフォルトで false に設定されています。