Class: Parse::Constraint::ArrayElemMatchConstraint

Inherits:
Parse::Constraint 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 Attribute Summary

Attributes inherited from Parse::Constraint

#operand, #operation, #operator, #value

Instance Method Summary collapse

Methods inherited from Parse::Constraint

#as_json, constraint_keyword, create, formatted_value, #formatted_value, #initialize, #key, #precedence, register, #to_s

Constructor Details

This class inherits a constructor from Parse::Constraint

Instance Method Details

#buildHash

Returns the compiled constraint using aggregation pipeline.

Returns:

  • (Hash)

    the compiled constraint using aggregation pipeline.



1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
# File 'lib/parse/query/constraints.rb', line 1213

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_matchArrayElemMatchConstraint

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:



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

register :elem_match