Definition
Returns the value of an expression for the first document in a window.
Note
Disambiguation
This page describes $first when used as a window function.
You can also use $first in these other contexts:
$first (accumulator), used in grouping to return the first value from each group.$first (expression), which returns the first element of an array.
Syntax
{ $setWindowFields: { ... output: { <field>: { $first: <expression> } } } }
Behavior
The $first window function has the following behaviors for null and missing values:
$firstconverts missing field values tonull.$firstreturnsnullfor empty windows.
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 identify the highest-rated movie in each year. Each document includes a field showing the title of the highest-rated movie 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: { topRatedMovieInYear: { $first: "$title", window: { documents: [ "unbounded", "unbounded" ] } } } } }, { $project: { _id: 0, title: 1, year: 1, "imdb.rating": 1, topRatedMovieInYear: 1 } }, { $sort: { year: 1, "imdb.rating": -1 } } ] )
In the preceding pipeline:
$matchfilters for movies from 1999-2001 with an IMDb rating of 8.5 or higher.$setWindowFieldspartitions movies byyearand sorts them byimdb.ratingin descending order. The stage uses$firstwith a window defined asdocuments: [ "unbounded", "unbounded" ]to return the title of the highest-rated movie in each year's partition.$projectincludes onlytitle,year,imdb.rating, andtopRatedMovieInYearin the output.$sortsorts the results by year and rating.