$percentile

Calculates the percentile of numerical values that match a filtering criteria, useful for identifying statistical thresholds such as median or percentiles.

Syntax

{ $percentile: { input: <field_or_expression>, p: [<percentile_values>], method: <method> } }

Parameters

inputexpressionrequired

Specifies the numerical data to calculate the percentile from

parrayrequired

Array of percentile values (between 0 and 1) to calculate

methodstringrequired

Interpolation method to use - "approximate" or "continuous"

Examples

Calculate the 50th percentile of sales volume

Calculate the 50th percentile (median) of total sales volume within sales categories

Query:

db.stores.aggregate([{ $unwind: "$sales.salesByCategory" }, { $group: { _id: null, medianSales: { $percentile: { input: "$sales.salesByCategory.totalSales", p: [0.5], method: "approximate" } } } }])

Output:

Documents with medianSales array containing the 50th percentile value

Calculate multiple percentiles

Calculate the 25th, 50th, and 75th percentiles of total sales across all stores

Query:

db.stores.aggregate([{ $group: { _id: null, percentiles: { $percentile: { input: "$sales.totalSales", p: [0.25, 0.5, 0.75], method: "approximate" } } } }])

Output:

Documents with percentiles array containing 25th, 50th, and 75th percentile values

Related