Definition
$medianNew in version 7.0.
Returns an approximation of the median (50th percentile) value of documents in a group.
The $median accumulator is available in these stages:
Note
Disambiguation
This page describes $median when used as an accumulator. Accumulators return an aggregated value across a group of input documents.
You can also use $median in these other contexts:
$median (expression), which returns the median of an array of values within a single document.$median (window function), which is used in the$setWindowFieldsstage to return the median value from documents in a window.
Syntax
{ $median: { input: <number>, method: <string> } }
Command Fields
$percentile takes the following fields:
Field | Type | Necessity | Description |
|---|---|---|---|
| Expression | Required |
|
| String | Required | The method that |
Behavior
When used as an accumulator, $median:
Calculates a single result for all the documents in the group.
Uses the t-digest algorithm for calculation of approximate percentiles. Approximation is necessary to calculate the median using a data structure of bounded size.
Calculation Considerations
When used as an accumulator, $median always uses an approximation algorithm. As a result, the computed percentiles $median returns on the same data set might differ on each run, due to pseudorandomness in the t-digest approximation algorithm. Additionally, $median may return a value that differs slightly from the true statistical median.
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 $median to calculate the median IMDb rating of Action movies per year from 2000 to 2004:
db.movies.aggregate( [ { $match: { genres: "Action", year: { $gte: 2000, $lte: 2004 }, "imdb.rating": { $gt: 0 } } }, { $group: { _id: "$year", medianRating: { $median: { input: "$imdb.rating", method: "approximate" } } } }, { $sort: { _id: 1 } } ] )
In the preceding pipeline: