- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $first (aggregation)
$first (aggregation)¶
On this page
Definition¶
-
$first¶ Returns the value that results from applying an expression to the first document in a group of documents that share the same group by key. Only meaningful when documents are in a defined order.
$firstis only available in the$groupstage.$firsthas the following syntax:For more information on expressions, see Expressions.
Behavior¶
When using $first in a $group stage, the output
value depends on the order of the documents coming into pipeline. To
guarantee a defined order, the $group pipeline stage should
follow a $sort stage.
Missing Values¶
The documents in a group may be missing fields or may have fields with missing values.
- If there are no documents from the prior pipeline stage, the
$groupstage returns nothing. - If the field that the
$firstaccumulator is processing is missing,$firstreturnsnull.
See the missing data example.
Examples¶
Use in $group Stage¶
Create the sales collection:
Grouping the documents by the item field, the following operation
uses the $first accumulator to compute the first sales date for
each item:
The operation returns the following results:
Missing Data¶
Some documents in the badData collection are missing fields, other
documents are missing values.
Create the badData collection:
Query the badData collection, grouping the output on the item
field:
The $sort stage orders the documents and passes them to the
$group stage.
$first selects the first document from each output group:
- The
_id: nullgroup is included. - When the accumulator field,
$quantityin this example, is missing,$firstreturnsnull.