For AI agents: a documentation index is available at https://www.mongodb.com/es/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.
Docs Menu

$percentile (expression)

$percentile

Returns one or more percentile values computed over an array of numbers.

Note

Disambiguation

This page describes $percentile when used as an expression, which calculates percentile values over an array of input values.

You can also use $percentile in these other contexts:

{
$percentile: {
input: <expression>,
p: [ <expression1>, <expression2>, ... ],
method: <string>
}
}
Field
Type
Description

input

Array

Can be either:

  • An expression that resolves to an array. For example, $scores, where the document field $scores contains an array of numeric values.

  • An array of expressions, each of which evaluates to a numeric value. For example, [ "$field1", "$field2", "$field3" ].

$percentile calculates percentile values across all numeric values in the array. Non-numeric values are ignored.

p

Expression

$percentile calculates a percentile value for each element in p. These elements specify the quantiles to compute and must be numeric values in the range 0.0 to 1.0, inclusive.

$percentile returns results in the same order as the elements in p.

method

String

The method that MongoDB uses to calculate the percentile value. The method must be 'approximate'.

When used as an expression, $percentile always uses an accurate percentile calculation algorithm rather than an approximate one, even when method: 'approximate' is specified. This is because expressions operate over arrays of bounded size where it is acceptable to keep all of the input values in memory.

Create a testScores collection:

db.testScores.insertMany( [
{ studentId: "2345", scores: [ 62, 81, 80, 75, 68 ] },
{ studentId: "2356", scores: [ 60, 83, 79, 72, 65 ] },
{ studentId: "2358", scores: [ 67, 82, 78, 70, 84 ] },
{ studentId: "2367", scores: [ 64, 72, 77, 58, 91 ] },
{ studentId: "2369", scores: [ 60, 53, 72, 85, 63 ] }
] )

The following pipeline uses $percentile to calculate the 25th, 50th, and 75th percentile test scores for each student:

db.testScores.aggregate( [
{
$project: {
_id: 0,
studentId: 1,
testPercentiles: {
$percentile: {
input: "$scores",
p: [ 0.25, 0.5, 0.75 ],
method: 'approximate'
}
}
}
}
] )

In the preceding pipeline, $project with $percentile computes the 25th, 50th, and 75th percentile of each student's scores array and returns them as testPercentiles.