Class: Parse::Constraint::ArrayFirstConstraint

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

Overview

Note:

This constraint uses MongoDB aggregation pipeline with $arrayElemAt. While $expr expressions cannot utilize field indexes, aggregation enables positional array access not available in standard Parse queries.

First element constraint - match based on the first element of an array. Uses MongoDB aggregation with $arrayElemAt.

q.where :tags.first => "rock" # first element equals "rock"

Instance Method Summary collapse

Instance Method Details

#build ⇒ Hash

Returns the compiled constraint using aggregation pipeline.

Returns:

  • (Hash) —

    the compiled constraint using aggregation pipeline.



2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
# File 'lib/parse/query/constraints.rb', line 2130

def build
  val = formatted_value
  field_name = Parse::Query.format_field(@operation.operand)

  # Handle pointer values. Wrap field reference in $ifNull so a missing
  # field is treated as [] (yielding null from $arrayElemAt) rather than
  # propagating a Missing value through the pipeline.
  if val.respond_to?(:id)
    compare_val = val.id
    pipeline = [
      {
        "$match" => {
          "$expr" => {
            "$eq" => [
              { "$arrayElemAt" => [{ "$map" => {
                "input" => { "$ifNull" => ["$#{field_name}", []] },
                "as" => "p",
                "in" => "$$p.objectId",
              } }, 0] },
              compare_val,
            ],
          },
        },
      },
    ]
  elsif val.is_a?(Parse::Pointer)
    compare_val = val.id
    pipeline = [
      {
        "$match" => {
          "$expr" => {
            "$eq" => [
              { "$arrayElemAt" => [{ "$map" => {
                "input" => { "$ifNull" => ["$#{field_name}", []] },
                "as" => "p",
                "in" => "$$p.objectId",
              } }, 0] },
              compare_val,
            ],
          },
        },
      },
    ]
  else
    pipeline = [
      {
        "$match" => {
          "$expr" => {
            "$eq" => [
              { "$arrayElemAt" => [{ "$ifNull" => ["$#{field_name}", []] }, 0] },
              val,
            ],
          },
        },
      },
    ]
  end

  { "__aggregation_pipeline" => pipeline }
end

#first ⇒ ArrayFirstConstraint

A registered method on a symbol to create the constraint.

Examples:

q.where :tags.first => "rock"

Returns:



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

register :first