# AggregateCommand.allElementsTrue(value: Expression[]): Object

支持端:小程序 2.7.4, 云函数 0.8.1, Web

聚合操作符。输入一个数组,或者数组字段的表达式。如果数组中所有元素均为真值,那么返回 true,否则返回 false。空数组永远返回 true

# 参数

# value: Expression[]

[<expression>]

# 返回值

# Object

# API 说明

语法如下:

allElementsTrue([<expression>])

# 示例代码

假设集合 test 有如下记录:

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

下面的代码使用 allElementsTrue(),判断 array 字段中是否均为真值:

const $ = db.command.aggregate
db.collection('price')
  .aggregate()
  .project({
    isAllTrue: $.allElementsTrue(['$array'])
  })
  .end()

返回结果如下:

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