db.command.aggregate.allElementsTrue
1. Operator Description
Description: Takes an array or an expression that resolves to an array. Returns true
if all elements in the array are truthy; otherwise, returns false
. An empty array always returns true
.
Declaration: db.command.aggregate.allElementsTrue([expression])
2. Operator Parameters
Field | Type | Required | Description |
---|---|---|---|
- | <Array>Expression | Required | A string expression is in the form of $ + specified field . |
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 allElementsTrue()
to determine whether all elements in the array
field are truthy:
// 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({
isAllTrue: $.allElementsTrue(['$array'])
})
.end()
console.log(res.data)
}
The returned result is as follows:
{ "_id": 1, "isAllTrue": true }
{ "_id": 2, "isAllTrue": true }
{ "_id": 3, "isAllTrue": false }
{ "_id": 4, "isAllTrue": false }
{ "_id": 5, "isAllTrue": false }
{ "_id": 6, "isAllTrue": true }