Definition
Returns an array containing the first n elements within a window.
Note
Disambiguation
This page describes $firstN when used as a window function.
You can also use $firstN in these other contexts:
$firstN (accumulator), used in grouping to return the firstnelements from each group.$firstN (expression), which returns the specified number of elements from the beginning of an array.
Syntax
{ $setWindowFields: { ... output: { <field>: { $firstN: { input: <expression>, n: <expression> } } } } }
Options
Field | Type | Description |
|---|---|---|
| Expression | The |
| Expression | The number of elements that If the window contains fewer than |
Behavior
Null and Missing Values
$firstNdoes not filter out null values.$firstNconverts missing values to null.
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.
This example uses $setWindowFields to partition movies by year, sort them by imdb.rating in descending order, and return the first three movies from each year. Each movie also includes a field that shows the three highest-rated movie titles released in that year:
db.movies.aggregate( [ { $match: { year: { $in: [ 1999, 2000, 2001 ] }, "imdb.rating": { $gte: 8.5 } } }, { $setWindowFields: { partitionBy: "$year", sortBy: { "imdb.rating": -1 }, output: { topThreeMoviesInYear: { $firstN: { input: "$title", n: 3 }, window: { documents: [ "unbounded", "unbounded" ] } } } } }, { $project: { _id: 0, title: 1, year: 1, "imdb.rating": 1, topThreeMoviesInYear: 1 } }, { $sort: { year: 1, "imdb.rating": -1 } } ] )
The preceding pipeline:
Uses the
$matchstage to filter the results to movies released between the years 1999 and 2001 with an IMDb rating of 8.5 or higher.Uses
$setWindowFieldsto partition movies byyearand sort them byimdb.ratingin descending order. The stage uses$firstNwithn: 3to createtopThreeMoviesInYearfrom a window defined asdocuments: [ "unbounded", "unbounded" ].Uses
$projectto include only thetitle,year,imdb.rating, andtopThreeMoviesInYearfields in the output.Uses
$sortto sort the results by year and rating.