mongodb/mongoid · error

eager_load cannot use $lookup aggregation because the follow

Error message

eager_load cannot use $lookup aggregation because the following associations reside in a different cluster or database than #{klass} (client: #{klass.client_name}, database: #{klass.database_name}): #{offender_descriptions.join(', ')}. Falling back to #includes behavior.

What it means

Error "eager_load cannot use $lookup aggregation because the following associations reside in a different cluster or database than #{klass} (client: #{klass.client_name}, database: #{klass.database_name}): #{offender_descriptions.join(', ')}. Falling back to #includes behavior." thrown in mongodb/mongoid.

Source

Thrown at lib/mongoid/association/eager_loadable.rb:44

        docs.tap do |d|
          preload(criteria.inclusions, d) if eager_loadable?
        end
      end

      # Load the associations for the given documents using $lookup.
      #
      # If any of the associated collections reside in a different cluster or
      # database than the root class, falls back to the #includes behavior and
      # logs a warning.
      #
      # @return [ Array<Mongoid::Document> ] The given documents.
      def eager_load_with_lookup
        offenders = inclusions_unreachable_by_lookup
        if offenders.any?
          offender_descriptions = offenders.map do |offender|
            "#{offender.name} (client: #{offender.klass.client_name}, database: #{offender.klass.database_name})"
          end
          Mongoid.logger.warn(
            'eager_load cannot use $lookup aggregation because the following associations ' \
            "reside in a different cluster or database than #{klass} " \
            "(client: #{klass.client_name}, database: #{klass.database_name}): " \
            "#{offender_descriptions.join(', ')}. Falling back to #includes behavior."
          )
          return eager_load(docs_for_lookup_fallback)
        end

        through_inclusions = criteria.inclusions.select do |association|
          association.is_a?(Association::Referenced::HasOneThrough) ||
            association.is_a?(Association::Referenced::HasManyThrough)
        end

        if through_inclusions.any?
          through_names = through_inclusions.map { |association| ":#{association.name}" }
          Mongoid.logger.warn(
            "#{through_names.join(', ')} are :through associations and do not support " \
            '$lookup-based eager loading. All inclusions for this query will be preloaded ' \

View on GitHub (pinned to 0da0e23d71)

When it happens

Trigger: Thrown at lib/mongoid/association/eager_loadable.rb:44 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of mongodb/mongoid@0da0e23d71 (2026-08-23). Data as JSON: /api/errors/3c7e5fe015212dc1. Report an issue: GitHub.