$divide (Division)
Last updated: 2026-10-09
$divide (Division)
$divide performs division in aggregation expressions with two arguments: the dividend and the divisor. It is often used to compute unit prices, per-capita values, or percentages, for example dividing two $sum results to get a ratio. Notably, dividing by zero does not throw — it returns null, unlike most programming languages. Any null or missing argument also yields null. $divide accepts integers, doubles, and Decimals, and the result is usually a double.
| Category | Math |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $divide: [ <expression1>, <expression2> ] }
⚙️ Parameters
| dividend | A numeric value or an expression resolving to one. |
|---|---|
| divisor | The denominator expression; a zero divisor makes the result null. |
Returns:The quotient of the two numbers; null when the divisor is zero
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $divide: compute average price per item
db.orders.aggregate([
{ $project: {
avgPrice: { $divide: ['$total', '$quantity'] }
} }
])
Output:
{ '_id': 1, 'avgPrice': 25 }
{ '_id': 2, 'avgPrice': 9 }
📌 Notes
- A zero divisor yields null instead of throwing
- Integer division produces a double; combine with $round or $trunc when rounding is needed
- Any null or missing argument yields null
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QDoes $divide throw when dividing by zero?
ANo — it returns null; use $ifNull when you need a default.
QWhat type does integer division return?
AThe result is a double, so 5 divided by 2 gives 2.5 rather than truncating.
QHow do I get a ratio from two $sum results?
APass them straight into $divide after computing both sums in $group, then divide in $project.