Module: Mongoid::Matcher::ElemMatch Private

Defined in:
lib/mongoid/matcher/elem_match.rb

Overview

This module is part of a private API. You should avoid using this module if possible, as it may be removed or be changed in the future.

In-memory matcher for $elemMatch expression.

Class Method Summary collapse

Class Method Details

.matches?(_exists, value, condition) ⇒ true | false, Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns whether a value satisfies an $elemMatch expression.

Parameters:

  • exists (true | false)

    Not used.

  • value (Object | Array<Object>)

    The value to check.

  • expr (Hash)

    The $elemMatch condition predicate.

Returns:

  • (true | false)

    Whether the value matches.

  • (Boolean)


18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/mongoid/matcher/elem_match.rb', line 18

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)
        rescue Mongoid::Errors::InvalidFieldOperator => exc
          raise Mongoid::Errors::InvalidElemMatchOperator.new(exc.operator)
        end
      end
    end
    false
  end
end