$median (Median Accumulator)
Last updated: 2026-10-09
$median (Median Accumulator)
$median is an accumulator returning the median of a numeric field within a group, available since MongoDB 7.0. The median is the middle value when sorted and is robust to outliers. The method option picks approximate (faster) or exact (precise) computation.
| Category | Accumulators |
|---|---|
| MongoDB Version | 7.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $group: { _id: <key>, med: { $median: { input: "$field", method: "approximate" } } } }
Returns:Median value of the group
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $median: median salary per department
db.salaries.aggregate([
{ $group: { _id: '$dept', med: { $median: { input: '$salary', method: 'approximate' } } } }
])
Output:
{ "_id": "ENG", "med": 42000 }
📌 Notes
- Requires MongoDB 7.0 or later
- method supports approximate and exact algorithms
- Missing fields are ignored; input should be numeric
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhich version does $median require?
AMongoDB 7.0 or later.
QWhat is the difference between approximate and exact?
Aapproximate uses a fast quantile algorithm; exact computes precisely at higher cost.
QHow do $median and $percentile relate?
A$median is the 50th percentile; $percentile computes any percentile.