> For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

# $first (accumulator operator)

## Definition

Returns the result of an [expression](https://www.mongodb.com/docs/manual/reference/mql/expressions.md#std-label-aggregation-expressions) 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:

- [`$bucket`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucket.md#mongodb-pipeline-pipe.-bucket)

- [`$bucketAuto`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucketauto.md#mongodb-pipeline-pipe.-bucketAuto)

- [`$group`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#mongodb-pipeline-pipe.-group)

**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)`](https://www.mongodb.com/docs/manual/reference/expression/first.md#mongodb-expression-exp.-first), which returns the first element of an array.

- [`$first (window function)`](https://www.mongodb.com/docs/manual/reference/mql/window-functions/first.md#mongodb-window-window.-first), which is used in the [`$setWindowFields`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/setwindowfields.md#mongodb-pipeline-pipe.-setWindowFields) stage to return a value for the first document in a window.

## Syntax

```javascript
{ $first: <expression> }
```

## Behavior

### Define Document Order

To define document order for `$first` in a grouping stage, add a preceding [`$sort`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#mongodb-pipeline-pipe.-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 [`$group`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#mongodb-pipeline-pipe.-group) stage returns nothing.

- If the field that the `$first` accumulator is processing is missing, `$first` returns `null`.

For example, consider the following documents in the `badData` collection, where some documents are missing fields:

```javascript
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:

```javascript
db.badData.aggregate( [
   { $sort: { item: 1, price: 1 } },
   {
      $group: {
         _id: "$item",
         inStock: { $first: "$quantity" }
      }
   }
] )

```

**Output:**

```javascript
[
  { _id: null, inStock: 5 },
  { _id: 'album', inStock: '' },
  { _id: 'cd', inStock: null },
  { _id: 'tape', inStock: 4 }
]

```

`$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](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-sample-mflix). For details on how to load this dataset into your self-managed MongoDB deployment, see [Load the Sample Dataset](https://www.mongodb.com/docs/manual/sample-data/load-sample-data-local.md#std-label-sample-dataset-local). 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:

```javascript
db.movies.aggregate( [
   { $sort: { year: 1, title: 1 } },
   { $unwind: "$genres" },
   {
      $group: {
         _id: "$genres",
         firstMovieTitle: { $first: "$title" },
         firstMovieYear: { $first: "$year" }
      }
   },
   { $sort: { _id: 1 } },
   { $limit: 5 }
] )

```

**Output:**

```javascript
[
  {
    _id: 'Action',
    firstMovieTitle: 'The Perils of Pauline',
    firstMovieYear: 1914
  },
  {
    _id: 'Adventure',
    firstMovieTitle: 'Robin Hood',
    firstMovieYear: 1922
  },
  {
    _id: 'Animation',
    firstMovieTitle: 'Winsor McCay, the Famous Cartoonist of the N.Y. Herald and His Moving Comics',
    firstMovieYear: 1911
  },
  {
    _id: 'Biography',
    firstMovieTitle: 'Regeneration',
    firstMovieYear: 1915
  },
  {
    _id: 'Comedy',
    firstMovieTitle: 'Winsor McCay, the Famous Cartoonist of the N.Y. Herald and His Moving Comics',
    firstMovieYear: 1911
  }
]

```

In the preceding pipeline:

- [`$sort`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#mongodb-pipeline-pipe.-sort) orders movies by `year` in ascending order, then `title` in alphabetical order.

- [`$unwind`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/unwind.md#mongodb-pipeline-pipe.-unwind) creates a separate document for each genre in the `genres` array, maintaining the sort order established by the previous stage.

- [`$group`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#mongodb-pipeline-pipe.-group) with `$first` returns the `title` and `year` of the first movie (earliest by year, then alphabetically by title) for each genre.

- A second [`$sort`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#mongodb-pipeline-pipe.-sort) sorts the results alphabetically by genre.

- [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) restricts the output to 5 genres.
