Class: Parse::Constraint::ArrayElemMatchConstraint

Inherits:
Constraint
  • Object
show all
Defined in:
lib/parse/query/constraints.rb

Overview

Note:

While $elemMatch is a standard MongoDB query operator, Parse Server's REST API query endpoint does not support it directly (returns "bad constraint"). This constraint uses aggregation pipeline to work around this limitation. Aggregation is efficient for complex multi-field element matching that would otherwise require multiple queries or client-side filtering.

Element match constraint for arrays of objects. Matches documents where at least one array element matches all specified criteria.

# Find posts where comments array has an approved comment by the user q.where :comments.elem_match => { author: user, approved: true }

# Find items where tags array has a tag with specific properties q.where :tags.elem_match => { name: "featured", priority: { "$gt" => 5 } }

Instance Method Summary collapse

Instance Method Details

#build ⇒ Hash

Returns the compiled constraint using aggregation pipeline.

Returns:

  • (Hash) —

    the compiled constraint using aggregation pipeline.



1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
# File 'lib/parse/query/constraints.rb', line 1976

def build
  val = formatted_value
  unless val.is_a?(Hash)
    raise ArgumentError, "#{self.class}: Value must be a hash of criteria for element matching"
  end

  field_name = Parse::Query.format_field(@operation.operand)

  # Convert any Parse objects to pointers in the criteria
  converted_val = convert_criteria(val)

  # Build the aggregation pipeline with $elemMatch
  # Parse Server doesn't support $elemMatch as a native query constraint,
  # but it works within aggregation pipeline $match stages
  pipeline = [
    {
      "$match" => {
        field_name => {
          "$elemMatch" => converted_val,
        },
      },
    },
  ]

  { "__aggregation_pipeline" => pipeline }
end

#elem_match ⇒ ArrayElemMatchConstraint

A registered method on a symbol to create the constraint. Uses aggregation pipeline since Parse Server doesn't support $elemMatch in queries.

Examples:

q.where :comments.elem_match => { author: user, approved: true }

Returns:



1973
# File 'lib/parse/query/constraints.rb', line 1973

register :elem_match