Definition
Returns an array of percentile values for the specified percentiles within a window.
Note
Disambiguation
This page describes $percentile when used as a window
function.
You can also use $percentile in these other contexts:
$percentile (accumulator), which returns an aggregated array of percentile values across a group of input documents.$percentile (expression), which calculates percentile values over an array of input values.
Syntax
{ $setWindowFields: { ... output: { <field>: { $percentile: { input: <expression>, p: [ <expression1>, <expression2>, ... ], method: <string> }, } } } }
Options
Field | Type | Description |
|---|---|---|
| Expression | The field over which |
| Expression |
|
| String | The method that MongoDB uses to calculate the percentile value. The method must be |
Behavior
In $setWindowFields, $percentile returns a result for each document, but the results are computed over a window of documents.
Calculation Considerations
When used as a window function, $percentile 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.
The following example uses $percentile in a $setWindowFields stage to find Action movies in the top 10% of IMDB ratings for each year from 2002 to 2004.
db.movies.aggregate( [ { $match: { year: { $in: [ 2002, 2003, 2004 ] }, genres: "Action", "imdb.votes": { $gte: 5000 }, } }, { $setWindowFields: { partitionBy: "$year", output: { top10PctRatingForYear: { $percentile: { input: "$imdb.rating", p: [ 0.9 ], method: "approximate" }, window: { documents: [ "unbounded", "unbounded" ] } } } } }, { $match: { $expr: { $gte: [ "$imdb.rating", { $arrayElemAt: [ "$top10PctRatingForYear", 0 ] } ] } } }, { $project: { _id: 0, title: 1, year: 1, imdb_rating: "$imdb.rating", top10PctRatingForYear: 1 } }, { $sort: { year: 1, imdb_rating: -1 } } ] )
The preceding pipeline:
Uses
$matchto filter for Action movies released in 2002, 2003, or 2004 with at least 5,000 IMDB votes.Uses
$setWindowFieldsto partition movies byyear. Within each partition, the$percentileoperator computes the 90th percentile IMDB rating usingp: [0.9]and an unbounded window, stored intop10PctRatingForYear.Uses
$projectto include thetitle,year,imdb_rating, andtop10PctRatingForYearfields in the output.Uses
$sortto order the results by year ascending, then by IMDB rating descending.