MongoDB聚合运算符:$allElementsTrue

判断所有的数组元素是否为true,即对每个数组元素进行判断,如果数组的每个元素都为true,则返回true,否则返回false。注意:空数组返回true

语法

{ $allElementsTrue: [ <expression> ] }

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

使用

如果数组包含嵌套元素,也就是数组元素是数组,$allElementsTrue只对顶层数组进行判断,除了明确的false外,null0undefined也会被认为是false,其他值(包括非零数值和数组)均被认为是true

如:

  • { $allElementsTrue: [ [ true, 1, "someString" ] ] } 结果为true
  • { $allElementsTrue: [ [ [ false ] ] ] }结果为true
  • { $allElementsTrue: [ [ ] ] }结果为true
  • { $allElementsTrue: [ [ null, false, 0 ] ] }``结果为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 ] }
])

下面的聚合操作使用$allElementsTrue评估responses数组是否只包含true元素:

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

操作返回下面的结果:

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

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