$allElementsTrue (aggregation)

On this page本页内容

Definition定义

$allElementsTrue

Evaluates an array as a set and returns true if no element in the array is false. 将数组作为集合计算,如果数组中没有元素为false,则返回trueOtherwise, returns false. An empty array returns true.否则,返回false。空数组返回true

$allElementsTrue has the following syntax:语法如下所示:

{ $allElementsTrue: [ <expression> ] }

The <expression> itself must resolve to an array, separate from the outer array that denotes the argument list. <expression>本身必须解析为一个数组,与表示参数列表的外部数组分开。For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式

Behavior行为

If a set contains a nested array element, $allElementsTrue does not descend into the nested array but evaluates the array at top-level.如果集合包含嵌套数组元素,$allElementsTrue不会下降到嵌套数组中,而是在顶级对数组求值。

In addition to the false boolean value, $allElementsTrue evaluates as false the following: null, 0, and undefined values. false布尔值外,$allElementsTrue还将以下值计算为假:null0undefined的值。The $allElementsTrue evaluates all other values as true, including non-zero numeric values and arrays.$AllegerementStrue将所有其他值计算为true,包括非零数值和数组。

Example示例 Result
{ $allElementsTrue: [ [ true, 1, "someString" ] ] }   true
{ $allElementsTrue: [ [ [ false ] ] ] }   true
{ $allElementsTrue: [ [ ] ] }   true
{ $allElementsTrue: [ [ null, false, 0 ] ] }   false

Example示例

Create an example collection named survey with the following documents:使用以下文档创建名为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 ] }
])

The following operation uses the $allElementsTrue operator to determine if the responses array only contains values that evaluate to true:以下操作使用$allElementsTrue运算符来确定responses数组是否只包含计算结果为true的值:

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

The operation returns the following results:操作返回以下结果:

{ "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 }