Skip to content

$arrayElemAt

The $arrayElemAt operator returns the element at a specified index in an array.


📌 Syntax

{ "$arrayElemAt": [ <arrayExpression>, <index> ] }
  • Indexing starts at 0.
  • Negative indexes count from the end.

✅ Base Example – Get First Tag

📥 Input Document

{ "tags": ["sale", "new", "trending"] }

📌 Expression

{ "$arrayElemAt": ["$tags", 0] }

📤 Output

"sale"

✅ Base Example – Get Last Element

📥 Input Document

{ "tags": ["sale", "new", "trending"] }

📌 Expression

{ "$arrayElemAt": ["$tags", -1] }

📤 Output

"trending"

🧱 Ecommerce Example – Access Top-Scoring Review

📌 Pipeline

[
  {
    "$project": {
      "product": "$name",
      "topReview": { "$arrayElemAt": ["$reviews", 0] }
    }
  }
]

📥 Input Document

{
  "name": "Laptop",
  "reviews": [
    { "user": "Alice", "rating": 5 },
    { "user": "Bob", "rating": 4 }
  ]
}

📤 Output

{
  "product": "Laptop",
  "topReview": { "user": "Alice", "rating": 5 }
}

🔧 Common Use Cases

  • Access top/last items
  • Index-based lookups
  • Extract highlights or featured content

  • $slice, $filter, $map, $reduce

🧠 Notes

  • Index out of bounds returns null.
  • Combine with $size or $cond for safer access.