MongoDB $arrayElemAt

In MongoDB, the $arrayElemAt aggregation pipeline operator returns the element at the specified array index.

It accepts two arguments;

  • The array
  • The index of the element you want to retrieve

Example

Suppose we have a collection called posts with the following document:

{
	"_id" : 1,
	"title" : "Hello World!",
	"body" : "This is a test post for the purposes of testing",
	"tags" : [
		"html",
		"css",
		"sql",
		"xml"
	],
	"status" : null
}

In this document, the tags field contains an array.

We can use the $arrayElemAt operator to return an array element at a specific index.

Example:

db.posts.aggregate([
  {
    $project: {
      "tag": { $arrayElemAt: [ "$tags", 0 ] }
    }
  }
])

Result:

{ "_id" : 1, "tag" : "html" }

In this case, we return the first array element. Arrays are zero-based, and so 0 refers to the first element in the array.

Tip: From MongoDB 4.4, we can also use the $first operator to return the first element in an array.

Here’s an example of getting the second element:

db.posts.aggregate([
  {
    $project: {
      "tag": { $arrayElemAt: [ "$tags", 1 ] }
    }
  }
])

Result:

{ "_id" : 1, "tag" : "css" }

Negative Values for the Index

You can provide a negative value for the second argument. When you do this, $arrayElemAt counts backwards from the end of the array.

Example:

db.posts.aggregate([
  {
    $project: {
      "tag": { $arrayElemAt: [ "$tags", -1 ] }
    }
  }
])

Result:

{ "_id" : 1, "tag" : "xml" }

In this case, we get the last element in the array.

From MongoDB 4.4, we can also use the $last operator to get the last array element.

Combining with Other Operators

You can use $arrayElemAt with other operators to produce the results you require.

Here’s an example of combining it with the $binarySize operator to return the size of a specific array element.

db.posts.aggregate([
  {
    $project: {
      "tagsSize": { $binarySize: { $arrayElemAt: [ "$tags", 0 ] } }
    }
  }
])

Result:

{ "_id" : 1, "tagsSize" : 4 }