- Reference >
- Query, Update, Projection, and Aggregation Operators >
- $ (projection)
$ (projection)¶
-
$¶ The positional
$operator limits the contents of the<array>field that is included in the query results to contain the first matching element. To specify an array element to update, see the positional $ operator for updates.Used in the projection document of the
find()method or thefindOne()method:The
$projection operator limits the content of the<array>field to the first element that matches the query document.The
<array>field must appear in the query documentThe
<value>can be documents that contains query operator expressions.Only one positional
$operator can appear in the projection document.Only one array field can appear in the query document; i.e. the following query is incorrect:
Example
A collection
studentscontains the following documents:In the following query, the projection
{ "grades.$": 1 }returns only the first element greater than or equal to85for thegradesfield.The operation returns the following documents:
Although the array field
gradesmay contain multiple elements that are greater than or equal to85, the$projection operator returns only the first matching element from the array.Important
When the
find()method includes asort(), thefind()method applies thesort()to order the matching documents before it applies the positional$projection operator.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 the sort was applied to the elements of the array before the$projection operator.Example
A
studentscollection contains the following documents where thegradesfield is an array of documents; each document contain the three field namesgrade,mean, andstd:In the following query, the projection
{ "grades.$": 1 }returns only the first element with themeangreater than70for thegradesfield. The query also includes asort()to order by ascendinggrades.gradefield:The
find()method sorts the matching documents before it applies the$projection operator on thegradesarray. Thus, the results with the projected array elements do not reflect the ascendinggrades.gradesort order:Note
Since only one array field can appear in the query document, if the array contains documents, to specify criteria on multiple fields of these documents, use the $elemMatch (query) operator, e.g.:
See also