Skip to main content

db.command.aggregate.reverseArray

1. Operator Description

Function: Returns the given array in reverse order.

Declaration: db.command.aggregate.reverseArray(array)

2. Operator Parameters

FieldTypeRequiredDescription
-ExpressionRequiredThe parameter can be any expression that resolves to an array.

3. Sample Code

Suppose the collection stats contains the following records:

{
"_id": 1,
"sales": [1, 2, 3, 4, 5]
}

Retrieve sales in reverse order:

// 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
const _ = db.command

exports.main = async (event, context) => {
const res = await db
.collection('stats')
.aggregate()
.project({
reversed: $.reverseArray('$sales')
})
.end()
console.log(res.data)
}

The returned result is as follows:

{ "_id": 1, "reversed": [5, 4, 3, 2, 1] }