Definition
Returns the specified number of elements from the beginning of an array.
Note
Disambiguation
This page describes $firstN when used as an expression, which returns the specified number of elements from the beginning of an array.
You can also use $firstN in these other contexts:
$firstN (accumulator), used in grouping to return the firstnelements from each group.$firstN (window function), which is used in the$setWindowFieldsstage to return the firstnvalues from documents in a particular window.
Syntax
{ $firstN: { input: <expression>, n: <expression> } }
Options
Field | Type | Description |
|---|---|---|
| Expression | The array from which to return the first |
| Expression | The number of elements that |
Behavior
$firstNreturns elements in the same order they appear in the input array.$firstNdoes not filter outnullvalues in the input array.You cannot specify a value of
nless than1.If the specified
nis greater than or equal to the number of elements in theinputarray,$firstNreturns the entireinputarray.If
inputresolves to a non-array value, the aggregation operation errors.
Example
The examples on this page use data from the sample_mflix dataset. For details on how to load this dataset into your self-managed MongoDB deployment, see Load the Sample Dataset. If you made any modifications to the sample databases, you may need to drop and recreate the databases to run the examples on this page.
The following example uses the $firstN operator to return the first three cast members for each movie. The cast members are returned in the new field firstThreeCast created by $addFields.
db.movies.aggregate( [ { $match: { title: { $in: [ "The Godfather", "Spirited Away", "The Dark Knight" ] } } }, { $addFields: { firstThreeCast: { $firstN: { input: "$cast", n: 3 } } } }, { $project: { _id: 0, title: 1, cast: 1, firstThreeCast: 1 } }, { $sort: { title: 1 } } ] )
The preceding pipeline:
Uses
$matchto filter for three specific movies.Uses
$addFieldswith$firstNto create a new fieldfirstThreeCastcontaining the first three elements from thecastarray withn: 3.Uses
$projectto include only thetitle,cast, andfirstThreeCastfields in the output.Uses
$sortto sort the results by title.