Class: Parse::Constraint::ArrayLastConstraint

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.

Last element constraint - match based on the last element of an array. Uses MongoDB aggregation with $arrayElemAt and index -1.

q.where :tags.last => "pop" # last element equals "pop"

Instance Method Summary collapse

Instance Method Details

#build ⇒ Hash

Returns the compiled constraint using aggregation pipeline.

Returns:

  • (Hash) —

    the compiled constraint using aggregation pipeline.



2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
# File 'lib/parse/query/constraints.rb', line 2211

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",
              } }, -1] },
              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",
              } }, -1] },
              compare_val,
            ],
          },
        },
      },
    ]
  else
    pipeline = [
      {
        "$match" => {
          "$expr" => {
            "$eq" => [
              { "$arrayElemAt" => [{ "$ifNull" => ["$#{field_name}", []] }, -1] },
              val,
            ],
          },
        },
      },
    ]
  end

  { "__aggregation_pipeline" => pipeline }
end

#last ⇒ ArrayLastConstraint

A registered method on a symbol to create the constraint.

Examples:

q.where :tags.last => "pop"

Returns:



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

register :last