Skip to main content

db.command.aggregate.isArray

1. Operator Description

Function: Determines whether a given expression is an array and returns a boolean value.

Declaration: db.command.aggregate.isArray(expression)

2. Operator Parameters

FieldTypeRequiredDescription
-ExpressionRequiredThe parameter can be any aggregate expression.

3. Sample Code

Suppose the collection stats contains the following records:

{
"_id": 1,
"base": 10,
"sales": [ 1, 6, 2, 2, 5 ]
}
{
"_id": 2,
"base": 1,
"sales": 100
}

Calculate the total sales: if sales is a number, compute sales * base; if sales is an array, compute the product of the sum of the array elements and base.

// 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({
sum: $.cond({
if: $.isArray('$sales'),
then: $.multiply([$.sum(['$sales']), '$base']),
else: $.multiply(['$sales', '$base'])
})
})
.end()
console.log(res.data)
}

The returned result is as follows:

{ "_id": 1, "index": 160 }
{ "_id": 2, "index": 100 }