MongoDB聚合运算符:$anyElementTrue

$anyElementTrue运算符用来对数组元素进行逻辑判断,如果数组的任何一个元素为true则返回true,否则返回false。空数组返回false

语法

{ $anyElementTrue: [ <expression> ] }

必须是能够被解析为数组的表达式。

使用

  • 对于内嵌数组,$anyElementTrue值处理顶层元素,不会去判断内嵌数组。
  • 除了正常的false值外,$anyElementTrue会将null0undefined都认为是false,其他的值包括非零数值都会被认为是true

如:

表达式 返回
{ $anyElementTrue: [ [ true, false ] ] } true
{ $anyElementTrue: [ [ [ false ] ] ] } true
{ $anyElementTrue: [ [ null, false, 0 ] ] } false
{ $anyElementTrue: [ [ ] ] } false

举例

使用下面的脚本创建survey集合:

db.survey.insertMany([
   { "_id" : 1, "responses" : [ true ] },
   { "_id" : 2, "responses" : [ true, false ] },
   { "_id" : 3, "responses" : [ ] },
   { "_id" : 4, "responses" : [ 1, true, "seven" ] },
   { "_id" : 5, "responses" : [ 0 ] },
   { "_id" : 6, "responses" : [ [ ] ] },
   { "_id" : 7, "responses" : [ [ 0 ] ] },
   { "_id" : 8, "responses" : [ [ false ] ] },
   { "_id" : 9, "responses" : [ null ] },
   { "_id" : 10, "responses" : [ undefined ] }
])

使用$anyElementTrue运算符来判断responses数组是否包含true元素:

db.survey.aggregate(
   [
     { $project: { responses: 1, isAnyTrue: { $anyElementTrue: [ "$responses" ] }, _id: 0 } }
   ]
)

操作返回下面的结果:

{ "responses" : [ true ], "isAnyTrue" : true }
{ "responses" : [ true, false ], "isAnyTrue" : true }
{ "responses" : [ ], "isAnyTrue" : false }
{ "responses" : [ 1, true, "seven" ], "isAnyTrue" : true }
{ "responses" : [ 0 ], "isAnyTrue" : false }
{ "responses" : [ [ ] ], "isAnyTrue" : true }
{ "responses" : [ [ 0 ] ], "isAnyTrue" : true }
{ "responses" : [ [ false ] ], "isAnyTrue" : true }
{ "responses" : [ null ], "isAnyTrue" : false }
{ "responses" : [ undefined ], "isAnyTrue" : false }

你可能感兴趣的:(mongodb,mongodb,数据库)