Skip to main content

db.command.aggregate.arrayElemAt

1. Operator Description

Function: Returns the element at the specified array index.

Declaration: db.command.aggregate.arrayElemAt([array, index])

2. Operator Parameters

FieldTypeRequiredDescription
-<Array>ExpressionYesThe first element array can be any expression that resolves to an array. The second element index can be any expression that resolves to an integer.

Notes:

If the value is positive, arrayElemAt returns the element at the position index. If the value is negative, arrayElemAt returns the element at the position index counting from the end of the array.

3. Sample Code

Suppose the collection exams contains the following records:

{ "_id": 1, "scores": [80, 60, 65, 90] }
{ "_id": 2, "scores": [78] }
{ "_id": 3, "scores": [95, 88, 92] }

Calculate the score of the first exam and the score of the last exam for each:

// Sample code in the Cloud Function environment
const tcb = require('@cloudbase/node-sdk')
const app = tcb.init({
env: 'xxx'
})

const db = app.database()
const $ = db.command.aggregate

exports.main = async (event, context) => {
const res = await db
.collection('exams')
.aggregate()
.project({
first: $.arraElemAt(['$scores', 0]),
last: $.arraElemAt(['$scores', -1])
})
.end()
console.log(res.data)
}

The returned result is as follows:

{ "_id": 1, "first": 80, "last": 90 }
{ "_id": 2, "first": 78, "last": 78 }
{ "_id": 3, "first": 95, "last": 92 }