w3resource
MongoDB Tutorial

MongoDB Aggregation Set Operator - $anyElementTrue

MongoDB: $anyElementTrue

The MongoDB $anyElementTrue operators takes a single argument expression. i.e. a set and returns true if any elements of the set evaluate to true; otherwise, returns false. An empty array returns false.

Syntax:

{ $anyElementTrue: [ <expression> ] }
  • When a set contains a nested array element, the $anyElementTrue does not descend into the nested array but evaluates the array at top-level.
  • For the boolean value false, $anyElementTrue evaluates as false the following: null, 0, and undefined values. The $anyElementTrue 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: $anyElementTrue

The following aggregation operation uses the $anyElementTrue operator to determine if the replies array contains any value that evaluates to true.

> db.survey_collection.aggregate(
...    [
...      { $project: { replies: 1, isAnyTrue: { $anyElementTrue: [ "$replies" ] }, _id: 0 } }
...    ]
... );

After the operation, following result will be returned by the $anyElementTrue operator.

> db.survey_collection.aggregate(
...    [
...      { $project: { replies: 1, isAnyTrue: { $anyElementTrue: [ "$replies" ] }, _id: 0 } }
...    ]
... );
{ "replies" : [ null ], "isAnyTrue" : false }
{ "replies" : [ [ ] ], "isAnyTrue" : true }
{ "replies" : [ ], "isAnyTrue" : false }
{ "replies" : [ [ false ] ], "isAnyTrue" : true }
{ "replies" : [ 1, true, "seven" ], "isAnyTrue" : true }
{ "replies" : [ true, false ], "isAnyTrue" : true }
{ "replies" : [ [ 0 ] ], "isAnyTrue" : true }
{ "replies" : [ null ], "isAnyTrue" : false }
{ "replies" : [ true ], "isAnyTrue" : true }
{ "replies" : [ 0 ], "isAnyTrue" : false }

Previous: $setIsSubset
Next: $allElementsTrue



New Content: Composer: Dependency manager for PHP, R Programming