Open In App

MongoDB $arrayElemAt Operator

MongoDB provides different types of array expression operators that are used in the aggregation pipeline stages and $arrayElemAt operator is one of them. This operator is used to return the element present on the specified index of the given array. 

Syntax: 



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

Here, the array must be a valid expression until it resolves to an array and index must be a valid expression until it resolves to an integer.

 Examples:



In the following examples, we are working with:

Database: GeeksforGeeks

Collection: arrayExample

Document: three documents that contain the details in the form of field-value pairs.

Using $arrayElemAt Operator:

In this example, we are going to find the elements of the array(i.e., the value of fruits field) on the specified index using $arrayElemAt operator. 

db.arrayExample.aggregate([
... {$match: {name: "Bongo"}},
... {$project: {
... firstItem: {$arrayElemAt: ["$fruits", 0]},
... lastItem: {$arrayElemAt: ["$fruits", -1]}}}])

Using $arrayElemAt Operator in the Embedded Document:

In this example, we are going to find the elements of the array(i.e., the value of favGame.outdoorGames field) on the specified index using $arrayElemAt operator. 

db.arrayExample.aggregate([
... {$match: {name: "Piku"}},
... {$project: {
... firstItem: {$arrayElemAt: ["$favGame.outdoorGames", 0]},
... item: {$arrayElemAt: ["$favGame.outdoorGames", 2]}}}])

Article Tags :