mongodb/mongoid · error · Mongoid::Errors::InvalidQuery

$regex is required if $options is given: #{Errors::InvalidQu

Error message

$regex is required if $options is given: #{Errors::InvalidQuery.truncate_expr(condition)}

What it means

Error "$regex is required if $options is given: #{Errors::InvalidQuery.truncate_expr(condition)}" thrown in mongodb/mongoid.

Source

Thrown at lib/mongoid/matcher/field_expression.rb:25

    # @api private
    module FieldExpression
      # Returns whether a value satisfies a condition.
      #
      # @param [ true | false ] exists Whether the value exists.
      # @param [ Object ] value The value to check.
      # @param [ Hash | Object ] condition The condition predicate.
      #
      # @return [ true | false ] Whether the value matches.
      #
      # @api private
      module_function def matches?(exists, value, condition)
        if condition.is_a?(Hash)
          condition.all? do |k, cond_v|
            k = k.to_s
            if k.start_with?('$')
              if %w[$regex $options].include?(k)
                unless condition.key?('$regex')
                  raise Errors::InvalidQuery, "$regex is required if $options is given: #{Errors::InvalidQuery.truncate_expr(condition)}"
                end

                if k == '$regex'
                  if options = condition['$options']
                    cond_v = case cond_v
                             when Regexp
                               BSON::Regexp::Raw.new(cond_v.source, options)
                             when BSON::Regexp::Raw
                               BSON::Regexp::Raw.new(cond_v.pattern, options)
                             else
                               BSON::Regexp::Raw.new(cond_v, options)
                             end
                  elsif cond_v.is_a?(String)
                    cond_v = BSON::Regexp::Raw.new(cond_v)
                  end

                  FieldOperator.get(k).matches?(exists, value, cond_v)
                else

View on GitHub (pinned to 0da0e23d71)

When it happens

Trigger: Thrown at lib/mongoid/matcher/field_expression.rb:25 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/44d6967b5a1221a2. Report an issue: GitHub.