Navigation
This version of the documentation is archived and no longer supported.
$first (aggregation)
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.
$first is only available in the
$group stage.
$first has the following syntax:
For more information on expressions, see Expressions.
Behavior
When using $first in a $group stage, the
$group stage should follow a $sort stage to
have the input documents in a defined order.
Note
Although the $sort stage passes ordered documents as
input to the $group stage, $group is not
guaranteed to maintain this sort order in its own output.
Example
Consider a sales collection with the following documents:
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: