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

$elemMatch requires a Hash operand: #

Error message

$elemMatch requires a Hash operand: #{Errors::InvalidQuery.truncate_expr(condition)}

What it means

Raised by the in-memory $elemMatch matcher when the operand is not a Hash. $elemMatch takes a hash of predicates applied to each array element, so any other operand shape is rejected before element-wise matching.

Solutions

  1. Pass a Hash of query predicates to $elemMatch, e.g. { tags: { '$elemMatch' => { '$eq' => 'x' } } }
  2. Use a plain equality/other operator if only a single value needs matching
Defensive patterns

Strategy: type-guard

When it happens

Trigger: Thrown at lib/mongoid/matcher/elem_match.rb:20 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/57193bde1bc24032. Report an issue: GitHub.

Appendix: source

Thrown at lib/mongoid/matcher/elem_match.rb:20

  module Matcher
    # In-memory matcher for $elemMatch expression.
    #
    # @see https://www.mongodb.com/docs/manual/reference/operator/query/elemMatch/
    #
    # @api private
    module ElemMatch
      # Returns whether a value satisfies an $elemMatch expression.
      #
      # @param [ true | false ] exists Not used.
      # @param [ Object | Array<Object> ] value The value to check.
      # @param [ Hash ] expr The $elemMatch condition predicate.
      #
      # @return [ true | false ] Whether the value matches.
      #
      # @api private
      module_function def matches?(_exists, value, condition)
        unless condition.is_a?(Hash)
          raise Errors::InvalidQuery, "$elemMatch requires a Hash operand: #{Errors::InvalidQuery.truncate_expr(condition)}"
        end

        if value.is_a?(Array) && !value.empty?
          value.any? do |v|
            ElemMatchExpression.matches?(v, condition)
          end
        else
          # Validate the condition is valid, even though we will never attempt
          # matching it.
          condition.each do |k, _v|
            k = k.to_s
            next unless k.start_with?('$')

            begin
              ExpressionOperator.get(k)
            rescue Mongoid::Errors::InvalidExpressionOperator
              begin
                FieldOperator.get(k)

View on GitHub (pinned to 0da0e23d71)