- Reference >
- Query, Update, Projection, and Aggregation Operators >
- $elemMatch (projection)
$elemMatch (projection)¶
See also
-
$elemMatch¶ New in version 2.2.
The
$elemMatchprojection operator limits the contents of an array field that is included in the query results to contain only the array element that matches the$elemMatchcondition.Note
- The elements of the array are documents.
- If multiple elements match the
$elemMatchcondition, the operator returns the first matching element in the array. - The
$elemMatchprojection operator is similar to the positional$projection operator.
The examples on the
$elemMatchprojection operator assumes a collectionschoolwith the following documents:Example
The following
find()operation queries for all documents where the value of thezipcodefield is63109. The$elemMatchprojection returns only the first matching element of thestudentsarray where theschoolfield has a value of102:The operation returns the following documents:
- For the document with
_idequal to1, thestudentsarray contains multiple elements with theschoolfield equal to102. However, the$elemMatchprojection returns only the first matching element from the array. - The document with
_idequal to3does not contain thestudentsfield in the result since no element in itsstudentsarray matched the$elemMatchcondition.
The
$elemMatchprojection can specify criteria on multiple fields:Example
The following
find()operation queries for all documents where the value of thezipcodefield is63109. The projection includes the first matching element of thestudentsarray where theschoolfield has a value of102and theagefield is greater than10:The operation returns the three documents that have
zipcodeequal to63109:Documents with
_idequal to3and_idequal to4do not contain thestudentsfield since no element matched the$elemMatchcriteria.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$elemMatchprojection.
See also
$ (projection) operator