Definition
Returns the median (50th percentile) value from documents in a specified window. You can use $median in both document-based and range-based windows.
Note
Disambiguation
This page describes $median when used as a window function.
You can also use $median in these other contexts:
$median (accumulator), used in grouping to return the median value across a group of input documents.$median (expression), which returns the median of an array of values.
Syntax
{ $setWindowFields: { ... output: { <field>: { $median: { input: <expression>, method: <string> } } } } }
Command Fields
Field | Type | Necessity | Description |
|---|---|---|---|
| Expression | Required | Returns the values over which the median is calculated. |
| String | Required | The method that |
Behavior
Calculation Considerations
When $median is used as a window function, it always uses an accurate percentile calculation algorithm rather than an approximate one, even when method: "approximate" is specified.
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.
This example uses $setWindowFields to compute the median IMDb rating for each movie that belongs to all three of the Adventure, Comedy, and Drama genres. The window spans the previous year, the same year, and the following year (range [ -1, 1 ]):
db.movies.aggregate( [ { $match: { genres: { $all: ["Adventure", "Comedy", "Drama"] }, year: { $gte: 2000, $lte: 2005 } } }, { $setWindowFields: { sortBy: { year: 1 }, output: { medianRatingByYear: { $median: { input: "$imdb.rating", method: "approximate" }, window: { range: [ -1, 1 ] } } } } }, { $project: { _id: 0, title: 1, year: 1, genres: 1, "imdb.rating": 1, medianRatingByYear: 1 } }, { $sort: { year: 1, "imdb.rating": -1 } }, { $limit: 10 } ] )
In the preceding pipeline:
$matchfilters for movies that belong to all three of the Adventure, Comedy, and Drama genres, released between 2000 and 2005.$setWindowFieldssorts byyearin ascending order and applies$medianwith a range-based window of[ -1, 1 ]. Each movie'smedianRatingByYearis the medianimdb.ratingof movies in all three genres released within one year of it.$projectincludes only thetitle,year,genres,imdb.rating, andmedianRatingByYearfields.$sortsorts the results byyearin ascending order, then byimdb.ratingin descending order.$limitrestricts the output to 10 results to improve readability.