$allElementsTrue
New from version 4.0
The $allElementsTrue operator is used to check if all elements in an array evaluate to a true value.
Parameters
-
expression: An expression that evaluates to an array.
Example (MongoDB Shell)
The following example demonstrates the usage of $allElementsTrue to check if all elements in an array are true.
Create sample documents
db.collection.insert([ { "name": "John", "scores": [100, 90, 80] }, { "name": "Jane", "scores": [80, 85, 0] }, { "name": "Bob", "scores": [90, 95, null] } ])
Query example
db.collection.find({ "scores": { "$allElementsTrue": [{ "$gt": 0 }] } })
Output
[
{ "_id" : ObjectId("..."), "name" : "John", "scores" : [ 100, 90, 80 ] },
{ "_id" : ObjectId("..."), "name" : "Bob", "scores" : [ 90, 95, null ] }
]
In this example, the query checks if all elements in the scores array are greater than 0. The document with "name": "Jane" is excluded because the scores array contains a 0, which is a falsy value.
Code examples
To view a code example for using the $allElementsTrue command, choose the tab for the language that you want to use: