Definition
Returns the first element of an array.
Note
Disambiguation
This page describes $first when used as an expression, which returns the first element of an array.
You can also use $first in these other contexts:
$first (accumulator), used in grouping to return the first value from each group.$first (window function), used in the$setWindowFieldsstage to return a value for the first document in a window.
Syntax
{ $first: <expression> }
The <expression> must evaluate to an array.
Behavior
If the operand expression evaluates to an array,
$firstreturns the first element of that array.If the array is empty,
$firstreturnsnull.If the expression evaluates to
nullor refers to a missing field,$firstreturnsnull.
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 $first to return the top-billed actor for each movie. In the sample_mflix dataset, the cast array lists actors in billing order, so the first element is the top-billed actor:
db.movies.aggregate( [ { $match: { title: { $in: [ "The Godfather", "Pulp Fiction", "Forrest Gump" ] } } }, { $addFields: { topBilledActor: { $first: "$cast" } } }, { $project: { _id: 0, title: 1, cast: 1, topBilledActor: 1 } }, { $sort: { title: 1 } } ] )
In the preceding pipeline:
$matchfilters for three specific movies.$addFieldswith$firstcreates a new fieldtopBilledActorcontaining the first element of thecastarray.$projectincludes only thetitle,cast, andtopBilledActorfields in the output.$sortsorts the results by title.