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

$not argument must be a Hash or a regular expression: #

Error message

$not argument must be a Hash or a regular expression: #{Errors::InvalidQuery.truncate_expr(condition)}

What it means

Raised by Mongoid::Matcher::Not.matches? when the $not condition is neither a Regexp/BSON::Regexp::Raw nor a Hash of operators. These are the only forms $not accepts in memory matching; the faulting input is the condition of any other type.

Solutions

  1. Pass a Regexp or a Hash of operator conditions to $not
  2. Use $ne for scalar inequality instead of $not with a bare value
Defensive patterns

Strategy: type-guard

When it happens

Trigger: Thrown at lib/mongoid/matcher/not.rb:37 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/aec2e7987183ba2e. Report an issue: GitHub.

Appendix: source

Thrown at lib/mongoid/matcher/not.rb:37

      module_function def matches?(exists, value, condition)
        case condition
        when ::Regexp, BSON::Regexp::Raw
          !Regex.matches?(exists, value, condition)
        when Hash
          if condition.empty?
            raise Errors::InvalidQuery, "$not argument cannot be an empty hash: #{Errors::InvalidQuery.truncate_expr(condition)}"
          end

          condition.all? do |(k, cond_v)|
            k = k.to_s
            unless k.start_with?('$')
              raise Errors::InvalidQuery, "$not arguments must be operators: #{Errors::InvalidQuery.truncate_expr(k)}"
            end

            !FieldOperator.get(k).matches?(exists, value, cond_v)
          end
        else
          raise Errors::InvalidQuery, "$not argument must be a Hash or a regular expression: #{Errors::InvalidQuery.truncate_expr(condition)}"
        end
      end
    end
  end
end

View on GitHub (pinned to 0da0e23d71)