Introduction to MongoDB $arrayElemAt Operator

MongoDB is a document-oriented database management system that provides rich aggregation pipeline operations for document processing. In the aggregation pipeline, the $arrayElemAt operator is a very useful tool that can be used to retrieve elements at a specific position in an array.

The $arrayElemAt operator is one of the MongoDB aggregation pipeline operators, used to return a specific array element at a given position. The operator requires two parameters: the array to operate on and the index of the element to return.

Syntax

The syntax for using the $arrayElemAt operator in the aggregation pipeline is as follows:

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

Here, <array> is the array to operate on, and <idx> is the index of the element to return. Note that the index starts at 0.

Use cases

When using the aggregation pipeline, it is sometimes necessary to access a single element in an array. For example, if you want to retrieve a field from a nested document and that field is an array, you can use the $arrayElemAt operator to access an element in that array. Additionally, $arrayElemAt can be used to implement pagination in MongoDB.

Examples

Assume there is a collection named students containing the following documents:

{
  "_id": 1,
  "name": "Alice",
  "scores": [90, 85, 95, 80]
},
{
  "_id": 2,
  "name": "Bob",
  "scores": [80, 70, 75, 60]
},
{
  "_id": 3,
  "name": "Charlie",
  "scores": [95, 90, 85, 100]
}

Now, if we want to query the second score of each student, we can use the following aggregation pipeline:

db.students.aggregate([
  {
    $project: {
      _id: 0,
      name: 1,
      secondScore: { $arrayElemAt: ["$scores", 1] }
    }
  }
])

This aggregation pipeline uses the $project operator to process each document and uses the $arrayElemAt operator to retrieve the second score of each student. After running the above aggregation pipeline, the results are as follows:

{ "name": "Alice", "secondScore": 85 }
{ "name": "Bob", "secondScore": 70 }
{ "name": "Charlie", "secondScore": 90 }

Conclusion

This article introduced the $arrayElemAt operator in MongoDB. This operator can be used to easily access a single element in an array and to implement pagination in the aggregation pipeline.