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

# $bottom (accumulator operator)

## Definition

Returns the bottom element within a group according to the specified sort order.

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 `$bottom` when used as an **accumulator**. Accumulators return a single aggregated value across a group of input documents.

You can also use `$bottom` in these other contexts:

- [`$bottom (expression operator)`](https://www.mongodb.com/docs/manual/reference/operator/bottom.md#mongodb-expression-exp.-bottom), which returns the last element of an array based on a specified sort order.

- [`$bottom (window function)`](https://www.mongodb.com/docs/manual/reference/mql/window-functions/bottom.md#mongodb-window-window.-bottom), used in the [`$setWindowFields`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/setwindowfields.md#mongodb-pipeline-pipe.-setWindowFields) stage to return the bottom element from documents in a particular window.

## Syntax

```none
{
   $bottom:
      {
         sortBy: { <field1>: <sort order>, <field2>: <sort order> ... },
         output: <expression>
      }
}
```

| Field | Necessity | Description |
| --- | --- | --- |
| sortBy | Required | Defines the ranking order of elements within each group, with syntax similar to [`$sort`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#mongodb-pipeline-pipe.-sort). Does not affect the order of documents in pipeline output. |
| output | Required | Represents the output for each element in the group and can be any expression. |

## Behavior

### Null and Missing Values

`$bottom` does not filter out null values, and `$bottom` converts missing values to null.

Consider the following aggregation that returns the bottom document from a group of scores:

```javascript
db.aggregate( [
   {
      $documents: [
         { playerId: "PlayerA", gameId: "G1", score: 1 },
         { playerId: "PlayerB", gameId: "G1", score: 2 },
         { playerId: "PlayerC", gameId: "G1", score: 3 },
         { playerId: "PlayerD", gameId: "G1"},
         { playerId: "PlayerE", gameId: "G1", score: null }
      ]
   },
   {
      $group:
      {
         _id: "$gameId",
         playerId:
            {
               $bottom:
                  {
                     output: [ "$playerId", "$score" ],
                     sortBy: { "score": -1 }
                  }
            }
      }
   }
] )
```

**Output:**

```javascript
[
   {
      _id: 'G1',
      playerId: [ 'PlayerD', null ]
   }
]
```

In this example:

- [`$documents`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/documents.md#mongodb-pipeline-pipe.-documents) creates the literal documents that contain player scores.

- [`$group`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#mongodb-pipeline-pipe.-group) groups the documents by `gameId`. This example has only one `gameId`, `G1`.

- `PlayerD` has a missing score and `PlayerE` has a null `score`. These values are both considered as null.

- The `playerId` and `score` fields are specified as `output : ["$playerId"," $score"]` and returned as array values.

- Specify the ranking order with `sortBy: { "score": -1 }`.

- `PlayerD` and `PlayerE` tied for the bottom element. `PlayerD` is returned as the bottom `score`.

## Restrictions

### Memory Limit Considerations

Aggregation pipelines which call `$bottom` are subject to the [100 MB limit](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-limits.md#std-label-agg-memory-restrictions). If this limit is exceeded for an individual group, the aggregation fails with an error.

## 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.

### Find the Bottom Rating in a Genre

You can use the `$bottom` accumulator to find the lowest-rated movie in a single genre.

```javascript
db.movies.aggregate( [
   {
      $match : { genres: "Comedy" }
   },
   {
      $group:
         {
            _id: "Comedy",
            lowestRatedMovie:
               {
                  $bottom:
                  {
                     output: [ "$title", "$imdb.rating" ],
                     sortBy: { "imdb.rating": -1 }
                  }
               }
         }
   }
] )

```

**Output:**

```javascript
[ { _id: 'Comedy', lowestRatedMovie: [ 'Saving Christmas', 1.6 ] } ]

```

The example pipeline:

- Uses [`$match`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/match.md#mongodb-pipeline-pipe.-match) to filter the results on a single genre. In this case, `Comedy`.

- Uses [`$group`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#mongodb-pipeline-pipe.-group) to group all Comedy movies under a single `"Comedy"` group key.

- Specifies the fields that are output for `$bottom` with `output : ["$title", "$imdb.rating"]`.

- Uses `sortBy: { "imdb.rating": -1 }` to define the bottom element in each group as the one with the lowest rating.

- Uses `$bottom` to return the lowest-rated movie for the genre.

### Find the Bottom Rating Across Multiple Years

You can use the `$bottom` accumulator to find the lowest-rated movie for each year.

```javascript
db.movies.aggregate( [
   {
      $match: {
         "imdb.rating": { $exists: true },
         year: { $gte: 2010, $lte: 2012 }
      }
   },
   {
      $group:
      {
         _id: "$year",
         lowestRatedMovie:
            {
               $bottom:
                  {
                     output: [ "$title", "$imdb.rating" ],
                     sortBy: { "imdb.rating": -1 }
                  }
            }
      }
   },
   {
      $sort: { _id: 1 }
   }
] )

```

**Output:**

```javascript
[
  { _id: 2010, lowestRatedMovie: [ 'Khan the Con', 2.5 ] },
  {
    _id: 2011,
    lowestRatedMovie: [ 'Justin Bieber: Never Say Never', 1.6 ]
  },
  { _id: 2012, lowestRatedMovie: [ 'USS Seaviper', 2.5 ] }
]

```

The example pipeline:

- Uses [`$match`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/match.md#mongodb-pipeline-pipe.-match) to filter for movies from 2010-2012 that have an IMDb rating.

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

- Uses `$bottom` to return the lowest-rated movie for each year.

- Specifies the fields that are output for `$bottom` with `output : ["$title", "$imdb.rating"]`.

- Uses `sortBy: { "imdb.rating": -1 }` to define the bottom element in each group as the one with the lowest rating.

- Uses [`$sort`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#mongodb-pipeline-pipe.-sort) to sort the results by year in ascending order.
