$arrayElemAt (aggregation)

Definition

  • $arrayElemAt

New in version 3.2.

Returns the element at the specified array index.

$arrayElemAt has the following syntax:

  1. { $arrayElemAt: [ <array>, <idx> ] }

The <array> expression can be any valid expression as long as it resolves to an array.

The <idx> expression can be any valid expression as long as it resolves to an integer.

  • If positive, $arrayElemAt returns the element at theidx position, counting from the start of the array.
  • If negative, $arrayElemAt returns the element at theidx position, counting from the end of the array.If the idx exceeds the array bounds, $arrayElemAtdoes not return any result.

For more information on expressions, seeExpressions.

Behavior

For more information on expressions, seeExpressions.

ExampleResults
{ $arrayElemAt: [ [ 1, 2, 3 ], 0 ] }1
{ $arrayElemAt: [ [ 1, 2, 3 ], -2 ] }2
{ $arrayElemAt: [ [ 1, 2, 3 ], 15 ] }

Example

A collection named users contains the following documents:

  1. { "_id" : 1, "name" : "dave123", favorites: [ "chocolate", "cake", "butter", "apples" ] }
  2. { "_id" : 2, "name" : "li", favorites: [ "apples", "pudding", "pie" ] }
  3. { "_id" : 3, "name" : "ahn", favorites: [ "pears", "pecans", "chocolate", "cherries" ] }
  4. { "_id" : 4, "name" : "ty", favorites: [ "ice cream" ] }

The following example returns the first and last element in thefavorites array:

  1. db.users.aggregate([
  2. {
  3. $project:
  4. {
  5. name: 1,
  6. first: { $arrayElemAt: [ "$favorites", 0 ] },
  7. last: { $arrayElemAt: [ "$favorites", -1 ] }
  8. }
  9. }
  10. ])

The operation returns the following results:

  1. { "_id" : 1, "name" : "dave123", "first" : "chocolate", "last" : "apples" }
  2. { "_id" : 2, "name" : "li", "first" : "apples", "last" : "pie" }
  3. { "_id" : 3, "name" : "ahn", "first" : "pears", "last" : "cherries" }
  4. { "_id" : 4, "name" : "ty", "first" : "ice cream", "last" : "ice cream" }