Skip to main content

db.command.aggregate.anyElementTrue

1. Operator Description

Description: Takes an array or an expression that resolves to an array. Returns true if any element in the array is truthy; otherwise, returns false. An empty array always returns false.

Declaration: db.command.aggregate.anyElementTrue([expression])

2. Operator Parameters

FieldTypeRequiredDescription
-<Array>ExpressionRequiredaggregate expression

3. Sample Code

Suppose the collection test contains the following records:

{ "_id": 1, "array": [ true ] }
{ "_id": 2, "array": [ ] }
{ "_id": 3, "array": [ false ] }
{ "_id": 4, "array": [ true, false ] }
{ "_id": 5, "array": [ 0 ] }
{ "_id": 6, "array": [ "stark" ] }

The following code uses anyElementTrue() to determine whether the array field contains any truthy value:

// 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('price')
.aggregate()
.project({
isAnyTrue: $.anyElementTrue(['$array'])
})
.end()
console.log(res.data)
}

The returned result is as follows:

{ "_id": 1, "isAnyTrue": true }
{ "_id": 2, "isAnyTrue": false }
{ "_id": 3, "isAnyTrue": false }
{ "_id": 4, "isAnyTrue": true }
{ "_id": 5, "isAnyTrue": false }
{ "_id": 6, "isAnyTrue": true }