Definition
$percentileNew in version 7.0.
Returns an array of scalar values that correspond to specified percentile values.
Available in these stages:
Note
Disambiguation
This page describes
$percentilewhen used as an accumulator. Accumulators return an aggregated value across a group of input documents.You can also use
$percentilein these other contexts:$percentile (expression), which calculates percentile values over an array of input values.$percentile (window function), which is used in the$setWindowFieldsstage to return an array of percentile values for documents in a particular window.
Syntax
{ $percentile: { input: <expression>, p: [ <expression1>, <expression2>, ... ], method: <string> } }
Options
$percentile takes the following fields:
Field | Type | Necessity | Description |
|---|---|---|---|
| Expression | Required |
|
| Expression | Required |
|
| String | Required | The method that MongoDB uses to calculate the percentile value. The method must be |
Behavior
When used as an accumulator, $percentile:
Calculates one set of percentiles per group, aggregated across all documents in the group.
Uses the t-digest algorithm for calculation of approximate percentiles. Approximation is necessary to calculate percentiles using a data structure of bounded size.
Calculation Considerations
When used as an accumulator, $percentile always uses an approximation algorithm. Due to pseudorandomness in the t-digest approximation algorithm, the computed percentile values on the same data set might differ on each run. Additionally, $percentile may return values that differ slightly from the true statistical percentiles.
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.
Calculate Rating Percentiles by Genre
The following example uses the $percentile accumulator to calculate the 50th and 90th percentile IMDB ratings for movies in the Action and Drama genres:
db.movies.aggregate( [ { $unwind: "$genres" }, { $match: { genres: { $in: [ "Action", "Drama" ] }, "imdb.rating": { $exists: true } } }, { $group: { _id: "$genres", ratingPercentiles: { $percentile: { input: "$imdb.rating", p: [ 0.5, 0.9 ], method: "approximate" } } } }, { $sort: { _id: 1 } } ] )
The preceding pipeline:
Uses
$unwindto create a separate document for each genre in thegenresarray.Uses
$matchto filter for movies that are classified asActionorDramaand have an IMDB rating field.Groups movies by genre.
Uses
$percentileto calculate the 50th and 90th percentile IMDB ratings for each genre withp: [0.5, 0.9].Uses
$sortto order the output by genre name.
The output ratingPercentiles array contains two values: the 50th percentile and the 90th percentile IMDB rating for each genre.