Definition
Returns the result of an expression for the first document in a group of documents. Only meaningful when documents are in a defined order.
The $first accumulator is available in these stages:
Note
Disambiguation
This page describes $first when used as an accumulator. Accumulators return a single aggregated value like sum, maximum, or minimum across a group of input documents.
You can also use $first in these other contexts:
$first (expression), which returns the first element of an array.$first (window function), which is used in the$setWindowFieldsstage to return a value for the first document in a window.
Syntax
{ $first: <expression> }
Behavior
Define Document Order
To define document order for $first in a grouping stage, add a preceding $sort stage.
Missing Values
Documents in a group may be missing fields. $first handles missing values as follows:
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.
For example, consider the following documents in the badData collection, where some documents are missing fields:
db.badData.insertMany( [ { "_id": 1, "price": 6, "quantity": 6 }, { "_id": 2, "item": "album", "price": 5, "quantity": 5 }, { "_id": 7, "item": "tape", "price": 6, "quantity": 6 }, { "_id": 8, "price": 5, "quantity": 5 }, { "_id": 9, "item": "album", "price": 3, "quantity": '' }, { "_id": 10, "item": "tape", "price": 3, "quantity": 4 }, { "_id": 12, "item": "cd", "price": 7 } ] )
Query the badData collection, grouping the output on the item field:
db.badData.aggregate( [ { $sort: { item: 1, price: 1 } }, { $group: { _id: "$item", inStock: { $first: "$quantity" } } } ] )
$first selects the first document from each output group. Documents that are missing the item field are grouped together with a null value for the _id field. When the accumulator field is missing (quantity in this example), $first returns null.
Examples
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 sorts movies by year and title, then groups them by genre to find the earliest movie released in each genre:
db.movies.aggregate( [ { $sort: { year: 1, title: 1 } }, { $unwind: "$genres" }, { $group: { _id: "$genres", firstMovieTitle: { $first: "$title" }, firstMovieYear: { $first: "$year" } } }, { $sort: { _id: 1 } }, { $limit: 5 } ] )
In the preceding pipeline:
$sortorders movies byyearin ascending order, thentitlein alphabetical order.$unwindcreates a separate document for each genre in thegenresarray, maintaining the sort order established by the previous stage.$groupwith$firstreturns thetitleandyearof the first movie (earliest by year, then alphabetically by title) for each genre.A second
$sortsorts the results alphabetically by genre.$limitrestricts the output to 5 genres.