- Reference >
- Query, Update, Projection, and Aggregation Operators >
- $elemMatch (projection)
$elemMatch (projection)¶
See also
-
$elemMatch
¶ New in version 2.2.
The
$elemMatch
projection operator limits the contents of an array field that is included in the query results to contain only the array element that matches the$elemMatch
condition.Note
- The elements of the array are documents.
- If multiple elements match the
$elemMatch
condition, the operator returns the first matching element in the array. - The
$elemMatch
projection operator is similar to the positional$
projection operator.
The examples on the
$elemMatch
projection operator assumes a collectionschool
with the following documents:Example
The following
find()
operation queries for all documents where the value of thezipcode
field is63109
. The$elemMatch
projection returns only the first matching element of thestudents
array where theschool
field has a value of102
:The operation returns the following documents:
- For the document with
_id
equal to1
, thestudents
array contains multiple elements with theschool
field equal to102
. However, the$elemMatch
projection returns only the first matching element from the array. - The document with
_id
equal to3
does not contain thestudents
field in the result since no element in itsstudents
array matched the$elemMatch
condition.
The
$elemMatch
projection can specify criteria on multiple fields:Example
The following
find()
operation queries for all documents where the value of thezipcode
field is63109
. The projection includes the first matching element of thestudents
array where theschool
field has a value of102
and theage
field is greater than10
:The operation returns the three documents that have
zipcode
equal to63109
:Documents with
_id
equal to3
and_id
equal to4
do not contain thestudents
field since no element matched the$elemMatch
criteria.When the
find()
method includes asort()
, thefind()
method applies thesort()
to order the matching documents before it applies the projection.If an array field contains multiple documents with the same field name and the
find()
method includes asort()
on that repeating field, the returned documents may not reflect the sort order because thesort()
was applied to the elements of the array before the$elemMatch
projection.
See also
$ (projection)
operator