$all
On this page
-
$all
-
The
$all
operator selects the documents where the value of a field is an array that contains all the specified elements. To specify an$all
expression, use the following prototype:
Behavior
Equivalent to $and
Operation
Changed in version 2.6.
The $all
is equivalent to an $and
operation of the specified values; i.e. the following statement:
is equivalent to:
Nested Array
Changed in version 2.6.
When passed an array of a nested array (e.g. [ [ "A" ] ]
), $all
can now match documents where the field contains the nested array as an element (e.g. field: [ [ "A" ], ... ]
), or the field equals the nested array (e.g. field: [ "A" ]
).
For example, consider the following query [1]:
The query is equivalent to:
which is equivalent to:
As such, the $all
expression can match documents where the tags
field is an array that contains the nested array [ "ssl", "security" ]
or is an array that equals the nested array:
This behavior for $all
allows for more matches than previous versions of MongoDB. Earlier versions could only match documents where the field contains the nested array.
[1] | The $all expression with a single element is for illustrative purposes since the $all expression is unnecessary if matching only a single element. Instead, when matching a single element, a “contains” expression (i.e. arrayField: element ) is more suitable. |
Examples
The following examples use the inventory
collection that contains the documents:
Use $all
to Match Values
The following operation uses the $all
operator to query the inventory
collection for documents where the value of the tags
field is an array whose elements include appliance
, school
, and book
:
The above query returns the following documents:
Use $all
with $elemMatch
If the field contains an array of documents, you can use the $all
with the $elemMatch
operator.
The following operation queries the inventory
collection for documents where the value of the qty
field is an array whose elements match the $elemMatch
criteria:
The query returns the following documents: