- Reference >
- Operators >
- Query and Projection Operators >
- Array Query Operators >
- $elemMatch (query)
$elemMatch (query)¶
On this page
See also
Definition¶
-
$elemMatch¶ The
$elemMatchoperator matches documents that contain an array field with at least one element that matches all the specified query criteria.If you specify only a single
<query>condition in the$elemMatchexpression, and are not using the$notor$neoperators inside of$elemMatch,$elemMatchcan be omitted. See Single Query Condition.
Behavior¶
- You cannot specify a
$whereexpression in an$elemMatch. - You cannot specify a
$textquery expression in an$elemMatch.
Examples¶
Element Match¶
Given the following documents in the scores collection:
The following query matches only those documents where the results
array contains at least one element that is both greater than or equal
to 80 and is less than 85:
The query returns the following document since the element 82 is
both greater than or equal to 80 and is less than 85:
For more information on specifying multiple criteria on array elements, see Specify Multiple Conditions for Array Elements.
Array of Embedded Documents¶
This statement inserts documents into the survey collection:
The following query matches only those documents where the results
array contains at least one element with both product equal to
"xyz" and score greater than or equal to 8:
Specifically, the query matches the following document:
Single Query Condition¶
If you specify a single query predicate in the $elemMatch
expression, and are not using the $not or $ne
operators inside of $elemMatch, $elemMatch can be
omitted.
The following examples return the same documents.
With $elemMatch:
Without $elemMatch:
However, if your $elemMatch expression contains the
$not or $ne operators then omitting the
$elemMatch expression changes the documents returned.
The following examples return different documents.
With $elemMatch:
Without $elemMatch:
With $elemMatch, the first query returns these documents:
Without $elemMatch, the second query returns this
document:
The first query returns the documents where any product in the
results array is not "xyz". The second query returns the
documents where all of the products in the results array are not
"xyz".
Additional Examples¶
For additional examples in querying arrays, see:
For additional examples in querying, see:
See also