$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.

CategoryMath
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $divide: [ <expression1>, <expression2> ] }

⚙️ Parameters

dividendA numeric value or an expression resolving to one.
divisorThe 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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏