$arrayElemAt (Get Array Element by Index)

Last updated: 2026-10-09

$arrayElemAt (Get Array Element by Index)

$arrayElemAt returns the element at a given index position in an array. It is the core operator for position-based array access in aggregation expressions, often used to grab the first item of an order, the last element of an array, or a specific position inside $project. Indexes start at 0, negative indexes count from the end, and out-of-range access returns null instead of throwing. Unlike $first/$last, $arrayElemAt can reach any position, making it more flexible.

CategoryArray
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $arrayElemAt: [ <array>, <index> ] }

⚙️ Parameters

arrayThe array, or an expression resolving to an array.
indexAn integer index; negative values count from the end, -1 is the last element.

Returns:The element at the given index; null if out of range or the array is null

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// $arrayElemAt: get the first item of an order
db.orders.aggregate([
  { $project: {
      firstItem: { $arrayElemAt: ['$items', 0] }
  } }
])

Output:

{ '_id': 1, 'firstItem': { 'sku': 'A01', 'qty': 2 } }
{ '_id': 2, 'firstItem': { 'sku': 'B02', 'qty': 1 } }

📌 Notes

More hands-on cases coming soon.

📚 Related Tutorials

❓ FAQ

QHow do I get the last element of an array with $arrayElemAt?
AUse -1 as the index, e.g. { $arrayElemAt: ['$arr', -1] }, without computing the length first.
QDoes an out-of-range index throw an error?
ANo — it returns null. Wrap with $ifNull to supply a default.
QWhat is the difference between $arrayElemAt and $first?
A$first always takes the first element; $arrayElemAt takes any index, including negatives, so it is more flexible.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏