MongoDB Aggregation Set Operator - $allElementsTrue
MongoDB : $allElementsTrue
The MongoDB $allElementsTrue operators take a single argument expression. i.e. a set and returns true if no element in the array is false. Otherwise, returns false. An empty array returns true.
Syntax:
{ $allElementsTrue: [ <expression> ] }
- When a set contains a nested array element, the $allElementsTrue does not descend into the nested array but evaluates the array at top-level.
- For the boolean value false, $allElementsTrue evaluates as false the following: null, 0, and undefined values. The $allElementsTrue evaluates all other values as true, including non-zero numeric values and arrays.
Sample collection survey_collection
{ "_id" : 1, "replies" : [ null ] }
{ "_id" : 2, "replies" : [ [ ] ] }
{ "_id" : 3, "replies" : [ ] }
{ "_id" : 4, "replies" : [ [ false ] ] }
{ "_id" : 5, "replies" : [ 1, true, "seven" ] }
{ "_id" : 6, "replies" : [ true, false ] }
{ "_id" : 7, "replies" : [ [ 0 ] ] }
{ "_id" : 8, "replies" : [ null ] }
{ "_id" : 9, "replies" : [ true ] }
{ "_id" : 10, "replies" : [ 0 ] }
Example : $allElementsTrue
The following aggregation operation uses the $allElementsTrue operator to determine if the replies array contains values that evaluate to true:
> db.survey_collection.aggregate(
... [
... { $project: { replies: 1, isAllTrue: { $allElementsTrue: [ "$replies" ] }, _id: 0 } }
... ]
... );
After the operation, following result will be returned by the $allElementsTrue operator.
> db.survey_collection.aggregate(
... [
... { $project: { replies: 1, isAllTrue: { $allElementsTrue: [ "$replies" ] }, _id: 0 } }
... ]
... );
{ "replies" : [ null ], "isAllTrue" : false }
{ "replies" : [ [ ] ], "isAllTrue" : true }
{ "replies" : [ ], "isAllTrue" : true }
{ "replies" : [ [ false ] ], "isAllTrue" : true }
{ "replies" : [ 1, true, "seven" ], "isAllTrue" : true }
{ "replies" : [ true, false ], "isAllTrue" : false }
{ "replies" : [ [ 0 ] ], "isAllTrue" : true }
{ "replies" : [ null ], "isAllTrue" : false }
{ "replies" : [ true ], "isAllTrue" : true }
{ "replies" : [ 0 ], "isAllTrue" : false }
Previous:
$anyElementTrue
Next:
MongoDB count() cursor method
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics