Skip to content
CAI
Software that uses CAICheck a score

mongodb/mongoid

64.1

Adequate · 28 September 2026

41.4k

lines of production code

Ruby

primary language

2

measurements over time

CAI band scale
CAI trend line
CAI lens gauges

What this system is

This system is a Ruby Object-Document Mapper (ODM) for MongoDB, providing a high-level interface for defining models, managing associations, and executing queries. It supports complex data relationships through embedded and referenced associations, including efficient eager loading and in-memory aggregation. The library also handles document persistence with atomic updates, transactions, and field-level encryption, while integrating seamlessly with Rails for background jobs and console workflows.

How it got here

2009–2012 — Rails integration and architectural refactoring

42 changes.

This period focused on deepening Rails integration through new generators, ActiveJob support, and console sandboxing, while simultaneously modernizing the codebase with a new configuration API and modularized internal structures. Significant architectural changes included refactoring atomic updates, error handling, and contextual query logic into focused modules, alongside the introduction of features like field-level encryption and in-memory aggregations.

2013–2017 — modular architecture refactoring

41 changes.

This period focused on decomposing Mongoid's monolithic core components—such as Criteria, Persistence, Validation, and Associations—into modular, single-responsibility classes to improve maintainability and separation of concerns. The work introduced significant internal restructuring across the codebase, including aggregation-based eager loading, batch operations for embedded documents, and comprehensive test coverage for all refactored modules. Additionally, the project expanded its capabilities with new Rake tasks for database management and field-level encryption, while updating CI infrastructure to support a wider range of Ruby, Rails, and MongoDB versions.

2018–2026 — integration test expansion and association features

18 changes.

This period focused on significantly expanding the integration test suite to cover core features such as associations, criteria queries, and contextual behaviors, while also introducing test support models and fixtures. Concurrently, new features were implemented, including in-memory query matching for embedded documents and eager loading support for has\_many and has\_one :through associations.

Features

Add Mongoid generator and boolean type mapping

Introduces a new \Mongoid::Generators::Base\ class to handle Mongoid integration within Rails applications, including template sourcing. Additionally, extends \Rails::Generators::GeneratedAttribute\ to map boolean attributes to \Mongoid::Boolean\ instead of the default CamelCase string, ensuring correct type generation for Mongoid models.

lib/rails/generators · high confidence

Add comprehensive performance benchmarking and profiling suite

The \perf\ directory now includes a complete suite of scripts for measuring and optimizing Mongoid performance. This adds \benchmark.rb\ and \benchmark\_ips.rb\ for standard and iterations-per-second (IPS) benchmarks across root documents, embedded associations (1-1, 1-n), and referenced associations (1-n, n-n). It also introduces \benchmark\_eager\_load.rb\ to specifically compare the performance of \includes\ versus the new \eager\_load\ method for various association types. Additionally, \profile.rb\ with \PerfTools\ integration allows for CPU profiling of key operations, supported by \gc\_suite.rb\ to manage garbage collection during measurements. These tools provide developers with concrete data on the performance impact of recent changes, such as the new eager loading implementation.

perf · high confidence

Add conditional model preloading utility for Rails integration

A new \lib/rails/mongoid.rb\ module provides utilities to manage model loading within the Rails environment. It introduces \preload\_models\, which conditionally loads all application models based on the \Mongoid.preload\_models\ configuration flag, allowing users to control whether models are preloaded in development versus production to optimize startup time and memory usage.

lib/rails · high confidence

Add eager loading support for has\_many and has\_one :through associations

Mongoid now supports efficient eager loading for \has\_many :through\ and \has\_one :through\ associations. This change introduces two-query eager preloader implementations (\Eager\ classes) and read-only proxies for both association types, allowing applications to load associated records in a single batch rather than triggering N+1 queries when iterating over parent documents.

_lib/mongoid/association/referenced/has\_many\_through, lib/mongoid/association/referenced/has\_one\through · high confidence

Add project scaffolding and linting configuration

The repository now includes essential development infrastructure: \.dockerignore\ and \.gitignore\ files to exclude build artifacts and sensitive data, \.rubocop.yml\ and \.rubocop\_todo.yml\ to enforce code style and static analysis with RuboCop (targeting Ruby 2.7+), \.rspec\ for test runner defaults, \.yardopts\ for documentation generation, and \AGENTS.md\ to define project structure and workflow guidelines.

(repo-wide) · high confidence

Add short timestamp variant for updated\_at

Introduces a new \Mongoid::Timestamps::Updated::Short\ module that stores the updated timestamp in a field named \u\_at\ while maintaining the \updated\_at\ alias for access. This allows users to opt into a shorter storage format for the updated timestamp without changing the public API.

lib/mongoid/timestamps/updated · high confidence

In-memory and null-context aggregation support for Enumerable criteria

Mongoid now supports aggregation methods (sum, avg, min, max, aggregates) on in-memory enumerable contexts (such as those returned by \#none or \#where with no database hits) and null contexts. The new \Mongoid::Contextual::Aggregable::Memory\ module implements these calculations locally using Ruby's Enumerable API, while \Mongoid::Contextual::Aggregable::None\ provides consistent default values (0 for sum, nil for avg/min/max) for empty sets. This change ensures that aggregation methods behave predictably regardless of whether the underlying data is fetched from MongoDB or held in memory.

lib/mongoid/contextual/aggregable · high confidence

New Rails integration components for ActiveJob, console sandboxing, and runtime logging

This change introduces several new files in the \lib/mongoid/railties\ directory to enhance Rails integration. It adds a \BsonObjectIdSerializer\ for ActiveJob to properly serialize and deserialize BSON ObjectIds in background jobs. It also implements a console sandbox mode (\console\_sandbox.rb\) that wraps the Rails console session in a transaction that is automatically aborted upon exit, preventing accidental data persistence during development. Additionally, a \ControllerRuntime\ module is added to track and log MongoDB query execution times in milliseconds alongside standard Rails controller logs. Finally, the \database.rake\ file is updated to define standard Rails database tasks (like \db:drop\, \db:purge\, \db:setup\, \db:test:prepare\) that delegate to corresponding Mongoid tasks, ensuring compatibility with Rails conventions.

lib/mongoid/railties · high confidence

New Rake tasks for database management and field-level encryption

Mongoid now provides a comprehensive set of Rake tasks under the \db:mongoid\ namespace to manage database schema and encryption keys. The \db:mongoid:database\ tasks allow users to create, drop, and purge collections and indexes, including specific support for creating and removing Atlas Search indexes and sharding collections. Additionally, a new \db:mongoid:encryption:create\_data\_key\ task enables the generation of data encryption keys for Field Level Encryption, supporting configuration of the KMS provider and key alternate names.

lib/mongoid/tasks · high confidence

New in-memory query matcher for embedded documents

Mongoid now supports in-memory evaluation of embedded document queries, allowing applications to filter embedded arrays and nested objects without relying solely on the database. This change introduces a comprehensive set of matcher modules in lib/mongoid/matcher that implement MongoDB query operators—including $all, $and, $or, $nor, $elemMatch, $exists, $regex, $mod, $type, and bitwise operators ($bitsAllSet, $bitsAllClear, etc.)—for use when querying embedded documents. The implementation includes a RegexpBudget module to prevent ReDoS attacks by bounding the time spent executing regular expressions during in-memory matching, and ensures Time comparisons use millisecond precision to align with BSON serialization behavior.

lib/mongoid/matcher · high confidence

Refactored association internals and introduced aggregation-based eager loading

The association module has been restructured into focused components (Accessors, Bindable, Builders, Constrainable, Depending, Eager, and EagerLoad) to improve code organization and maintainability. A significant new capability is the introduction of an in-memory aggregation pipeline for eager loading associations via Criteria\#eager\_load, which uses MongoDB's $lookup stages to fetch nested associations more efficiently. This includes support for discriminated inclusions (STI), embedded document distribution, and polymorphic preloading. Additionally, association accessors now handle selected fields from projections more robustly, and builder methods for one-to-one associations have been refined to better manage type specification and callback execution.

lib/mongoid/association · high confidence

Architecture

Persistence logic reorganized into modular components

The document persistence behavior has been refactored from a single monolithic module into distinct, focused modules (Creatable, Savable, Updatable, Deletable, Destroyable, Upsertable, and various atomic operation modules like Settable, Pushable, etc.). This structural change organizes how documents are created, saved, updated, deleted, and destroyed, as well as how atomic MongoDB operators ($set, $push, $inc, etc.) are applied, improving code maintainability and separation of concerns without altering the external API surface for these operations.

lib/mongoid/persistable · high confidence

Queryable module refactored into modular components

The internal query building logic in \lib/mongoid/criteria/queryable\ has been restructured into distinct, focused modules including \Aggregable\, \Expandable\, \Key\, \Mergeable\, \Optional\, \Pipeline\, \Selectable\, \Selector\, \Smash\, and \Storable\. This refactoring separates concerns for aggregation pipeline construction, condition expansion, key/operator handling, selector merging, and option storage, providing a cleaner internal architecture for building MongoDB queries without changing the external query API.

lib/mongoid/criteria/queryable · high confidence

Refactor embedded\_in association internals into dedicated modules

The internal implementation of the \embedded\_in\ association has been restructured to improve modularity and maintainability. The previous logic for binding/unbinding parent-child relationships, building objects, and proxying access has been extracted into three new, distinct files: \binding.rb\, \buildable.rb\, and \proxy.rb\. This change separates concerns, making the association's behavior easier to test and extend without altering the public API for users.

_lib/mongoid/association/embedded/embedded\in · high confidence

Refactor embeds\_many association internals into modular components

The internal implementation of the \embeds\_many\ association has been restructured to improve modularity and maintainability. The previous monolithic structure has been split into distinct, focused modules: \Binding\ handles the logic for linking and unlinking documents to their parent, \Buildable\ manages the instantiation of new embedded documents from attributes, and \Proxy\ serves as the transparent interface for interacting with the collection of embedded documents. This change isolates concerns within the association layer, making the codebase easier to test and extend without altering the public API surface for users.

_lib/mongoid/association/embedded/embeds\many · high confidence

Refactor query type-casting into modular extension files

The query type-casting logic previously embedded in the criteria queryable module has been extracted into dedicated extension files for each supported Ruby type (Array, BigDecimal, Boolean, Date, DateTime, Hash, NilClass, Numeric, Object, Range, Regexp, Set, String, Symbol, Time, and TimeWithZone). This structural change organizes the evolution and mongoization behavior for each class into its own module, improving maintainability and separation of concerns without altering the external query behavior.

lib/mongoid/criteria/queryable/extensions · high confidence

Refactored embeds\_one association internals into modular components

The internal implementation of the \embeds\_one\ association has been restructured to improve code organization and maintainability. The previous monolithic structure has been split into distinct, focused modules: \Binding\ handles the synchronization of inverse references between parent and child documents, \Buildable\ manages the instantiation and factory-based creation of embedded documents (including handling of selected fields), and \Proxy\ serves as the transparent interface for user-facing interactions like substitution and attribute updates. This refactoring isolates concerns, making the association logic easier to test and extend without changing the external API or behavior for users.

_lib/mongoid/association/embedded/embeds\_one, lib/mongoid/association/referenced/has\many · high confidence

Refactored query and persistence context into modular mixins

The \lib/mongoid/contextual\ directory has been restructured to replace monolithic context classes with a composition of focused mixin modules. New files include \Atomic\ for direct MongoDB update operators (e.g., $set, $inc), \Aggregable\ for aggregation methods, \Command\ for database command handling, \MapReduce\ for map/reduce operations, \Queryable\ for existence checks, and specific implementations for \Memory\, \Mongo\, and \None\ contexts. This change improves code organization and separation of concerns within the criteria execution layer.

lib/mongoid/contextual · high confidence

Behavioural changes

Comprehensive rewrite of Mongoid error handling and i18n support

The error handling system in lib/mongoid/errors has been completely refactored to support internationalization (i18n) and provide more specific, actionable feedback. All error classes now inherit from a new MongoidError base that composes messages from localized YAML keys (problem, summary, resolution) rather than hardcoded strings. This change introduces dozens of new, granular error types (such as AmbiguousRelationship, AttributeNotLoaded, Callback, ImmutableAttribute, and InvalidDotDollarAssignment) to replace generic exceptions, ensuring users receive precise diagnostics for issues like invalid query operators, configuration mistakes, or association conflicts. Additionally, a new ConfigRedactor utility automatically masks sensitive credentials (passwords, URIs) in error output to prevent accidental exposure.

lib/mongoid/errors · high confidence

Encapsulate index specifications in a dedicated class

Index definitions are now encapsulated within a new \Mongoid::Indexable::Specification\ class. This change introduces explicit handling for index option mappings (such as \expire\_after\_seconds\ to \expire\_after\) and supports aliases on specific options like \partial\_filter\_expression\, \weights\, and \wildcard\_projection\. The equality check for index specifications has been updated to perform a superficial comparison based on keys and names, rather than comparing all options, which allows for more flexible index declaration and prevents duplicate index errors when options differ only in non-critical ways.

lib/mongoid/indexable · high confidence

Extracted document lifecycle state management into a dedicated module

The document lifecycle state management logic (assigning, binding, building, loading, and creating modes) has been extracted from the main Mongoid::Threaded module into a new, dedicated \Mongoid::Threaded::Lifecycle\ module. This change isolates the thread-local state checks and execution blocks, making the threaded context handling more modular and easier to maintain without altering the external behavior of these lifecycle states.

lib/mongoid/threaded · high confidence

Localization now works when setting or updating a single attribute

Updating or setting a single localized attribute on a document now correctly persists the localized values, ensuring that translations are properly saved and retrieved when modifying individual fields rather than the entire document.

lib/mongoid · high confidence

Model generator now supports custom collection names and belongs\_to associations

The Mongoid model generator template has been updated to allow users to specify a custom collection name via the new \--collection\ option, which inserts a \store\_in\ directive into the generated class. Additionally, the generator now uses \belongs\_to\ for reference attributes instead of \embedded\_in\, ensuring that generated models correctly establish parent-child relationships via references rather than embedding.

lib/rails/generators/mongoid/model/templates · high confidence

Mongoid Evergreen CI configuration migrated to ERB templates and updated test matrix

The Evergreen continuous integration setup has been restructured to use ERB templates under \.evergreen/config/\ (axes, variants, commands, options) which are compiled into the final \config.yml\ via the \update-evergreen-configs\ script. The test matrix now covers MongoDB versions 3.6 through 9.0, Ruby versions 2.7 through 4.0 (including JRuby 9.4 and 10.0), and Rails versions up to 8.1. New scheduled build variants (\ruby-dev\ and \rails-master\) run bi-weekly against upcoming Ruby and Rails master branches to catch incompatibilities early, and the configuration includes support for testing against driver versions (current, master, stable, oldstable, min) and various topologies (standalone, replica set, sharded cluster).

.evergreen · high confidence

Mongoid model generator now includes timestamps and collection options by default

The \mongoid:model\ generator has been updated to include \:timestamps\ and \:collection\ as configurable class options, with timestamps enabled by default. This allows users to generate models that automatically include created\_at and updated\_at fields, and specify a custom MongoDB collection name, directly from the command line without needing to manually edit the generated code.

lib/rails/generators/mongoid/model · high confidence

New Rails generator produces modular Mongoid configuration files

The \mongoid:config\ generator now creates two separate files instead of a single \mongoid.yml\: a \config/initializers/mongoid.rb\ for code-based configuration (which loads version-specific defaults) and a \config/mongoid.yml\ for connection and driver settings. The YAML template has been restructured to use the modern \clients\ hierarchy (replacing the legacy \sessions\ structure) and includes comprehensive, commented-out examples for driver options such as authentication, SSL, compression, and timeouts. This change aligns the generated configuration with current MongoDB Ruby driver standards and allows for more flexible runtime configuration via the initializer.

lib/rails/generators/mongoid/config/templates · high confidence

New client factory and persistence context management

Mongoid introduces a dedicated client factory (\lib/mongoid/clients/factory.rb\) that centralizes database client creation, handling configuration merging, auto-encryption options, and driver platform metadata. Persistence behavior is now managed through a \PersistenceContext\ system (exposed via \lib/mongoid/clients/options.rb\), allowing documents to temporarily switch storage targets (collection, database, or client) using the \with\ method. Additionally, \lib/mongoid/clients/sessions.rb\ adds support for MongoDB sessions and transactions, including \transaction\ and \with\_session\ methods, along with transaction-specific callbacks like \after\_commit\ and \after\_rollback\ that trigger only when documents are modified within a transaction.

lib/mongoid/clients · high confidence

New configuration API and client management methods

The library introduces a new \Mongoid.configure\ method that allows users to set up configuration options, supporting both block arguments and blocks without arguments for Rails parity. It also adds convenience methods for managing database connections: \default\_client\ to retrieve the default client, \client(name)\ to get a named client, \disconnect\_clients\ to close all active connections, and \reconnect\_clients\ to re-establish them. Configuration options are now delegated directly from the \Mongoid\ module to the \Config\ singleton, simplifying access to settings like database names.

lib · high confidence

New configuration validators for client and async query settings

Mongoid now includes dedicated validators in \lib/mongoid/config/validators\ to enforce stricter configuration rules at startup. The new \Client\ validator ensures that every client configuration (including the default) specifies either a \uri\ or both \hosts\ and \database\, and raises an error if both a URI and standard connection options are mixed. The \AsyncQueryExecutor\ validator prevents invalid combinations by raising an error if \global\_executor\_concurrency\ is set while \async\_query\_executor\ is configured as \:immediate\. Additionally, the \Option\ validator rejects any unrecognized configuration keys, ensuring only valid options are accepted.

lib/mongoid/config/validators · high confidence

New validation for MongoDB index options and deprecation warning for geoHaystack

The index macro now validates that all provided options are recognized by the new \Mongoid::Indexable::Validators::Options\ module, explicitly supporting options such as \partial\_filter\_expression\, \collation\, and \wildcard\_projection\. Additionally, using the \geoHaystack\ index type now triggers a deprecation warning via \Mongoid::Warnings\, alerting users that this feature is deprecated.

lib/mongoid/indexable/validators · high confidence

Refactor attributes module into focused sub-modules

The lib/mongoid/attributes directory has been reorganized into distinct modules (Dynamic, Embedded, Nested, Processing, Projector, Readonly) to improve code structure and maintainability. This refactoring introduces specific behaviors: dynamic attributes now define reader/writer methods on first access via method\_missing; nested attributes (accepts\_nested\_attributes\_for) are processed after IDs are generated to support polymorphic types; readonly attributes now respect field projections and inherit correctly across subclasses; and a new Projector class handles MongoDB projection logic for attribute access checks.

lib/mongoid/attributes · high confidence

Refactor embedded atomic path generation to use store\_as and support empty list persistence

The atomic path generation logic for embedded documents has been refactored to determine the storage path based on the association's \store\_as\ option rather than the document's class name, ensuring correct path resolution when custom storage keys are used. Additionally, a new \position\_without\_document\ method has been added to the embedded many association path utility, enabling the system to persist an empty list when setting an \embeds\_many\ association to an empty value.

lib/mongoid/atomic/paths/embedded · high confidence

Refactored Mongoid::Criteria into modular mixin components

The internal structure of Mongoid::Criteria has been reorganized into distinct, single-responsibility modules to improve maintainability and clarity. Functionality is now split across new files: Findable handles document retrieval by ID, Includable manages eager loading logic (including the new $lookup aggregation support via eager\_load), Modifiable covers document creation and modification methods like create\_with and find\_or\_create\_by, and Permission adds strong parameters validation for query methods. Additional modules include Queryable for core query DSL and MQL generation, Scopable for default and named scope handling, Marshalable for serialization, Inspectable for debugging output, and Translator for value conversion. This refactoring isolates concerns, making the Criteria class easier to extend and test without altering the public API.

lib/mongoid/criteria · high confidence

Refactored atomic modification handling with conflict detection

The atomic update logic has been restructured into dedicated modifier classes that explicitly handle $set, $push, $pull, and $addToSet operations. This change introduces robust conflict detection to prevent invalid atomic commands, such as ensuring $set operations never target the \_id field and correctly handling conflicts between $set and $unset operations. It also improves array modification handling by using $pull with ID matching instead of $pullAll for embedded documents and properly managing double conflicting pushes, ensuring that atomic updates are generated correctly without database errors.

lib/mongoid/atomic · high confidence

Refactored atomic path generation for embedded and root documents

The atomic path logic for embedded and root documents has been restructured to improve clarity and correctness. For embedded documents, path generation now uses memoization to efficiently strip positional indices from the path string. For root documents, attempting to access an insert modifier now explicitly raises an InvalidPath error, preventing mixed association issues. Additionally, the positional operator update logic has been fixed to correctly handle arrays with more than ten objects, resolving a previous bug where updates were broken for larger collections.

lib/mongoid/atomic/paths · high confidence

Refactored belongs\_to association internals into modular components

The implementation of referenced belongs\_to associations has been restructured from a monolithic structure into distinct, focused modules: Binding, Buildable, Eager, and Proxy. This change introduces explicit handling for binding and unbinding inverse relationships (including polymorphic inverse types), separates the logic for building and querying associated documents, and implements a dedicated eager loader that resolves polymorphic types via the association resolver to prevent loading arbitrary constants from user-controlled data. Users benefit from cleaner association management, improved security in polymorphic eager loading, and more predictable behavior when substituting or nullifying association targets.

_lib/mongoid/association/referenced/belongs\to · high confidence

Refactored configuration system with Rails-style defaults and field-level encryption support

The configuration logic in lib/mongoid/config has been restructured into modular components (defaults, encryption, environment, introspection, options, validators). Users can now use \Mongoid::Config.load\_defaults(version)\ to apply Rails-style default settings for specific Mongoid versions (8.0, 8.1, 9.0, 9.1), which adjust feature flags like \legacy\_readonly\, \immutable\_ids\, and \autosave\_saves\_unchanged\_documents\. Additionally, the new \lib/mongoid/config/encryption.rb\ module enables automatic configuration of Client Side Field Level Encryption (FLE) by generating schema maps and metadata from model definitions, allowing encrypted fields to be handled seamlessly within the Mongoid configuration flow.

lib/mongoid/config · high confidence

Refactored embedded association internals and added batch operations

The embedded association logic has been restructured to improve performance and fix bugs. A new Batchable module was introduced to handle insert, clear, remove, and replace operations in batches, reducing database round-trips by using atomic MongoDB operators like $push/$each and $set. The cyclic association support was extracted into its own module, providing the \recursively\_embeds\_many\ and \recursively\_embeds\_one\ macros for self-referencing hierarchies. Additionally, the \embeds\_one\ association now supports a \:fallback\ option to handle nil values for singular associations, and the \embedded\_in\ association defaults the \:touch\ option to true to ensure parent documents are updated when embedded documents change.

lib/mongoid/association/embedded · high confidence

Refactored field definitions into dedicated classes with new encrypted and localized support

The field definition logic in lib/mongoid/fields has been restructured into specific classes: Standard, Foreign Key, Localized, and Encrypted. This change introduces native support for encrypted fields (allowing configuration of deterministic encryption, key IDs, and key alt names) and enhances localized fields with options to enforce presence and control fallback behavior. Additionally, foreign key handling is now encapsulated in its own class to better manage atomic changes and polymorphic relations, while validators are modularized via a macro.

lib/mongoid/fields · high confidence

Refactored has\_and\_belongs\_to\_many association internals

The has\_and\_belongs\_to\_many association implementation has been restructured to improve code organization and fix several behavioral issues. The association logic is now split into dedicated modules: \Binding\ handles the synchronization of inverse foreign keys between documents, \Buildable\ manages the creation and querying of associated documents, and \Eager\ handles preloading associations efficiently. The \Proxy\ class, which exposes the association to the user, has been updated to correctly handle custom primary keys when building or adding documents (MONGOID-5194), avoid populating the \changed\_attributes\ hash for foreign key changes to prevent false dirty tracking (MONGOID-4843), and alias \delete\_one\ to \delete\ for consistency. These changes ensure that HABTM associations behave more predictably regarding persistence, inverse relationships, and change tracking.

_lib/mongoid/association/referenced/has\_and\_belongs\_to\many · high confidence

Refactored has\_one association internals with new binding and buildable modules

The has\_one association implementation has been restructured to improve code organization and behavior. A new Binding class now explicitly handles the synchronization of inverse relationships between the parent and child documents during bind and unbind operations. The Buildable module replaces the previous builder pattern, providing a dedicated interface for constructing and querying associated documents, including support for polymorphic criteria and handling aggregation pipeline results. Additionally, the Eager loader and Proxy classes have been updated to work with these new components, ensuring that association loading, persistence, and substitution (including dependent destroy actions) function correctly within the refactored structure.

_lib/mongoid/association/referenced/has\one · high confidence

Refactored nested attributes handling into dedicated builder classes

The nested attributes logic for \accepts\_nested\_attributes\_for\ has been restructured into specific builder classes: \Mongoid::Association::Nested::Many\ for one-to-many associations and \Mongoid::Association::Nested::One\ for one-to-one associations, sharing common functionality via the \Buildable\ mixin. This change introduces support for a new \:fallback\ option on singular associations to handle nil values, adds a \:limit\ option to restrict the number of records in many-to-many nested attributes, and enforces immutability of the \\_id\ field on persisted documents (configurable via \Mongoid::Config.immutable\_ids\). It also ensures that deeply nested children are validated correctly and fixes issues where parent IDs were missing in \after\_destroy\ callbacks during nested attribute removal.

lib/mongoid/association/nested · high confidence

Refactored referenced association implementation into modular components

The referenced association logic has been restructured into distinct, focused modules to improve maintainability and clarity. The new \AutoSave\ module centralizes the logic for automatically persisting associated documents, including cycle detection and persistence context handling. \CounterCache\ now explicitly manages atomic increment/decrement callbacks for counter fields. \Syncable\ handles the synchronization of foreign keys on many-to-many relationships during save and destroy events. Additionally, \WithPolymorphicCriteria\ provides shared behavior for applying polymorphic search filters. These changes underpin the \BelongsTo\, \HasMany\, \HasOne\, \HasAndBelongsToMany\, and \Through\ association classes, ensuring consistent behavior for autosaving, caching, and key synchronization across all referenced association types.

lib/mongoid/association/referenced · high confidence

Refactored timestamp modules and added block-based timeless API

The timestamping logic has been restructured into separate \Created\ and \Updated\ modules, each handling their respective \created\_at\ and \updated\_at\ fields with distinct callbacks. A new block-based \timeless\ API is now available (e.g., \record.timeless { record.save }\) to temporarily suppress timestamp updates for specific operations, replacing the deprecated chained form. Additionally, \updated\_at\ is no longer overridden if it has been manually set before creation, and the \cache\_key\ method leverages \updated\_at\ to help fragment caches expire old views.

lib/mongoid/timestamps · high confidence

Refactored type casting and deprecated internal monkey patches in core extensions

The type-casting logic for core Ruby types (Array, BigDecimal, Date, Time, String, etc.) has been restructured into dedicated extension modules, introducing a consistent \mongoize\/\demongoize\ interface and adding support for new types like BSON::Vector and BSON::Decimal128. Simultaneously, numerous internal monkey-patch methods (such as \\_\_find\args\\\, \\\sortable\\\, and \\\_to\inc\\_\) have been deprecated to clean up the public API, while legacy methods like \Hash\#to\_criteria\ are replaced by \Criteria.from\_hash\.

lib/mongoid/extensions · high confidence

Refactored validation logic into modular, localized-aware components

The validation subsystem in lib/mongoid/validatable has been restructured into distinct, specialized modules. The new AssociatedValidator now correctly handles embedded associations by skipping validation for destroyed or flagged-for-destroy documents, preventing errors when validating parent-child relationships. The NumericalityValidator has been updated to properly recognize BSON::Decimal128 as a numeric type and handles raw value casting to avoid issues with StringifiedSymbol fields. Additionally, the Presence, Format, and Length validators now include the Localizable mixin, ensuring that validations are applied to each locale of a localized field rather than the entire localized object, fixing previous bugs where localized nil or blank fields were not validated correctly.

lib/mongoid/validatable · high confidence

Updated Mongoid configuration generator to create mongoid.yml and mongoid.rb

The \mongoid:config\ generator now produces a \config/mongoid.yml\ file (renamed from the previous \database.mongo.yml\) and a \config/initializers/mongoid.rb\ initializer. The generator also includes logic to correctly resolve the Rails application name on Rails 6.1 and later, ensuring the generated configuration is properly named for the current project.

lib/rails/generators/mongoid/config · high confidence

Validation of field definition options and duplicate field handling

The field macro now validates the options passed during field definition, raising an error if an unknown option is provided. It also checks for duplicate field names, raising an exception if the \overwrite\ option is not set and \Mongoid.duplicate\_fields\_exception\ is enabled, otherwise issuing a warning. Additionally, a deprecation warning is issued if the \type\ option is set to \Symbol\.

lib/mongoid/fields/validators · high confidence

Test coverage

Added Mongoid integration example test; Added comprehensive test coverage for Mongoid contextual query operations; Added comprehensive test coverage for Mongoid type extensions; Added comprehensive test coverage for Mongoid validatable validators; Added comprehensive test coverage for atomic persistence operations; Added comprehensive test coverage for the Criteria::Queryable module; Added integration test suite for Mongoid core features; Added integration tests for association behaviors; Added integration tests for atomic modifiers and conflict resolution; Added integration tests for criteria query behaviors; Added integration tests for empty result set behavior in Contextual classes; Added integration tests for range field persistence and collection options; Added shared test contexts for time zone and time type validation; Added test coverage for HasAndBelongsToMany association internals; Added test coverage for HasMany association internals; Added test coverage for HasOne association internals; Added test coverage for Mongoid Criteria modules; Added test coverage for Mongoid atomic modifiers and path resolution; Added test coverage for Mongoid client factory, options, sessions, and transactions; Added test coverage for belongs\_to association binding, building, and eager loading; Added test coverage for dynamic, embedded, nested, readonly, and projector attribute behaviors; Added test coverage for embedded association behaviors; Added test coverage for foreign key, localized, and standard field behaviors; Added test coverage for in-memory and None aggregation contexts; Added test coverage for nested association builders and atomic update preparation; Added test coverage for queryable type extensions; Added test coverage for referenced association types; Added test fixtures for encrypted Mongoid models; Added test suite documentation and configuration scaffolding; Added test support models for polymorphic reviews; Added test support models to spec/support/models; Added tests for ActiveJob ObjectId serialization and console sandbox mode; Added tests for DocumentsLoader state management and async execution; Added tests for Matcher extract\_attribute and RegexpBudget; Added tests for Mongoid configuration defaults, encryption, and environment loading; Added tests for Mongoid error classes and configuration redaction; Added tests for Mongoid index specification normalization and equality; Added tests for Mongoid relations proxy behavior; Added tests for Mongoid::Atomic::Paths::Root; Added tests for Rails controller runtime metrics; Added tests for Rails::Mongoid model preloading; Added tests for association accessors, builders, autosave, and fallback behaviors; Added tests for database and encryption rake tasks; Added tests for embedded association binding, building, and proxying; Added tests for embedded atomic path modifiers and positioning; Added tests for embeds\_many association binding, building, and proxy behaviors; Added tests for embeds\_one association binding, building, and proxy behavior; Added tests for has\_many/has\_one through association eager loading and proxy behavior; Added tests for short timestamp variants and Timeless behavior; New test infrastructure and support utilities.

Dependencies

Integrates Evergreen tools for CI configuration

The project now includes the Evergreen tools submodule (.mod/drivers-evergreen-tools), enabling the use of MongoDB's internal continuous integration infrastructure for testing and deployment workflows.

.mod · high confidence

Restructured test environment with new driver and Rails version configurations

The gemfiles directory has been reorganized to support testing against a wider range of MongoDB driver versions (stable, oldstable, master, and minimum versions) and Rails versions (6.0 through 8.1, plus master). New gemfiles explicitly pin specific Rails versions (e.g., \rails-6.0.gemfile\, \rails-8.1.gemfile\) and driver branches (e.g., \driver\_stable.gemfile\ pointing to \2.19-stable\, \driver\_min.gemfile\ pointing to \2.18-stable\). A shared \standard.rb\ helper centralizes common test and development dependencies like RSpec, Rubocop, and debugging tools, reducing duplication across the new configuration files.

gemfiles · high confidence

Updated dependency requirements for Ruby 2.7+ and MongoDB driver 2.18+

Mongoid now requires Ruby 2.7 or higher and the MongoDB Ruby driver version 2.18.0 or higher (up to 3.0.0). The ActiveModel dependency has been updated to support versions 5.1 through 8.1 (excluding 7.0.0), and concurrent-ruby is required at version 1.0.5 or higher. Additionally, the gemspec now includes metadata links for bug trackers and documentation, and development dependencies for BSON are specified.

(dependencies) · high confidence

Written by watchdog.canine.dev from the codebase's own history, inside the signed delivery this page is composed from.

How this codebase got here

Score

  • CAI 65 → 64 (-1.1)
  • Rubric changed (rubric-2026.09.8 → rubric-2026.09.16) — scores are not directly comparable.

Lenses

  • Code Health 97 → 97 (+0.1)
  • Architecture 100 → 72 (-27.2)
  • Maturity 56 → 57 (+0.2)
  • Readiness 70 → 67 (-3.3)
  • Security 63 → 69 (+6.2)

Resolved (9)

  • Concentrated knowledge decay
  • Database.shard_collections (cognitive 19) (lib/mongoid/tasks/database.rb)
  • Database.shard_collections (cyclomatic 17) (lib/mongoid/tasks/database.rb)
  • Documentation: contradicts the code (.evergreen/README.md)
  • Documentation: no installation or build instructions (README.md)
  • Documentation: no usage examples (README.md)
  • Many.update_nested_relation (cognitive 17) (lib/mongoid/association/nested/many.rb)
  • Off-boarding risk: anonymized user #1
  • TodoComment (lib/mongoid/association/referenced/has_many/proxy.rb)

New (9)

  • Database.shard_collections_for (cognitive 19) (lib/mongoid/tasks/database.rb)
  • Database.shard_collections_for (cyclomatic 17) (lib/mongoid/tasks/database.rb)
  • Off-boarding risk: anonymized user #1
  • Orphaned files with no living knowledge
  • Projects may be oversized for their cohesion
  • TodoComment (lib/mongoid/association/referenced/has_many/proxy.rb)
  • TodoComment (lib/mongoid/association/referenced/has_many/proxy.rb)
  • TodoComment (lib/mongoid/criteria/queryable/selectable.rb)
  • Typo in method name: 'reflect_on_all_association' (singular) vs 'reflect_on_all_associations' (plural). The instance method is missing the trailing 's'.

Changes since last survey

  • 2 commits — 2 feature/other, 0 fixes

By area

  • (root) — 1 commit
  • lib/mongoid — 1 commit

Notable commits

  • change: Merge commit from fork
  • change: Release Candidate: 9.1.1 (#6177)

Written by watchdog.canine.dev from the codebase's own history, inside the signed delivery this page is composed from.

Survey your own repository

mongodb/mongoid was measured the same way every project in this corpus was: the same rubric, at a pinned commit, with the result published in full. Point a surveyor at a repository you know and see whether you agree with it.

About this page

  • The score is its most recent published measurement, taken on 28 September 2026 at a pinned commit. It is not a live figure and does not change until the project is measured again.
  • Measured at commit 381d954edf3812f138e53b940123126619713a03 — the exact code this score is about.
  • Scored under rubric-2026.09.16 — the same rubric and the same method as every other entry in this index.
  • Measured by watchdog.canine.dev using codehealth-analyzer preprod-2d9048c36d26.