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

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

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

# 参数

# value: Expression[]

[<expression>]

# 返回值

# Object

# API 说明

语法如下:

anyElementTrue([<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" ] }

下面的代码使用 anyElementTrue(),判断 array 字段中是否含有真值:

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

返回结果如下:

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