The $divide operator divides one number by another in MongoDB aggregation pipelines. It is a core arithmetic operator for computing averages, ratios, rates, and normalized values directly inside your data.
01
Division
Divide dividend by divisor.
02
Syntax
Two operands in an array.
03
$project Stage
Compute new ratio fields.
04
Field References
Divide document fields.
05
Use Cases
Metrics, ratios, scaling.
06
Zero Safety
Guard against divide-by-zero.
Fundamentals
Definition and Usage
In MongoDB’s aggregation framework, the $divide operator performs division on two numeric expressions. For example, { $divide: [ 100, 4 ] } returns 25, and { $divide: [ "$revenue", "$quantity" ] } computes revenue per unit for each document. This is one of the most commonly used arithmetic operators for business metrics and data normalization.
💡
Beginner Tip
Think of $divide as MongoDB’s pipeline version of the / operator. The first value in the array is the dividend (top number), and the second is the divisor (bottom number). Use it inside expression stages like $project or $addFields.
Foundation
📝 Syntax
The $divide operator takes an array of two numeric expressions:
mongosh
{ $divide: [ <dividend>, <divisor> ] }
Syntax Rules
$divide — returns the quotient of the dividend divided by the divisor.
<dividend> — the number being divided (first array element).
<divisor> — the number you divide by (second array element).
Use it inside stages like $project, $addFields, or $set.
If either operand is null, the result is null.
If the divisor is 0, MongoDB throws an error — guard with $cond when needed.
⚠️ Watch Out: Division by Zero
If the divisor evaluates to zero, $divide throws an error and stops the pipeline. Check for zero before dividing:
$divide: [ 100, 4 ] → 25(valid)
$divide: [ 100, 0 ] → error(divide by zero!)
$divide: [ null, 5 ] → null(null input)
Cheat Sheet
⚡ Quick Reference
Question
Answer
Operator type
Aggregation expression operator (arithmetic)
Syntax
{ $divide: [ <dividend>, <divisor> ] }
Operands
Two numeric expressions in an array
Output
Quotient (number, or null)
Common stages
$project, $addFields, $set
Example
{
$divide: [ 100, 4 ]
}
Returns 25
Fields
{
$divide: [
"$revenue",
"$quantity"
]
}
Revenue per unit
Percentage
{
$divide: [
"$part",
"$total"
]
}
Ratio of part to total
Null input
{
$divide: [ null, 5 ]
}
Returns null
Hands-On
Examples Gallery
Walk through sample sales data, an aggregation pipeline, and the computed per-unit revenue step by step.
📚 Revenue Per Unit
Start with a simple sales collection and compute average revenue per unit sold with $project.
Sample Input Documents
Suppose you have a sales collection with revenue and quantity fields:
If quantity is zero, return null instead of dividing. This prevents pipeline errors on documents with missing or zero quantities.
Applications
🚀 Use Cases
Performance metrics — compute revenue per unit, cost per item, or average order value.
Data normalization — scale values by dividing by a maximum or total to get ratios between 0 and 1.
Financial analysis — calculate profit margins, expense ratios, and other division-based KPIs.
Rate calculations — derive hourly rates, speed, or throughput by dividing totals by time or count.
🧠 How $divide Works
1
MongoDB evaluates both operands
The pipeline resolves the dividend and divisor — field paths like "$revenue" or literal numbers.
Input
2
$divide computes the quotient
MongoDB divides the dividend by the divisor. If the divisor is zero, an error is thrown.
Transform
3
The result is stored in the pipeline
The quotient is written to the field you define in $project or $addFields.
Output
=
📊
Ratios and rates ready
You get computed metrics like per-unit revenue, completion ratios, or hourly rates for reports and dashboards.
Wrap Up
Conclusion
The $divide operator is a fundamental arithmetic tool in MongoDB aggregation pipelines. It lets you compute ratios, averages, and rates directly on your data — from revenue per unit to project completion percentages and hourly earnings.
For beginners, the key idea is simple: pass two values in an array — { $divide: [ dividend, divisor ] } — inside a stage like $project, and MongoDB returns the quotient. Always watch for zero divisors in your data.
Use $divide for per-unit, ratio, and rate calculations
Guard against zero divisors with $cond and $eq
Combine with $multiply to convert ratios to percentages
Use $round on results when displaying decimals
Test with zero, null, and fractional values
❌ Don’t
Divide by zero without checking the divisor first
Swap dividend and divisor order by mistake
Use $divide as a query filter outside expressions
Assume it converts non-numeric strings to numbers
Forget that null in either operand returns null
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about $divide
Use these points when computing ratios in MongoDB pipelines.
5
Core concepts
🔢01
Division
Dividend ÷ divisor.
Purpose
📝02
Array Syntax
{ $divide: [a, b] }
Syntax
🛠03
Pipeline Stages
$project, $addFields, $set.
Usage
💰04
Metrics Ready
Ratios, rates, averages.
Use case
⚠05
Zero Guard
Divisor 0 throws error.
Edge case
❓ Frequently Asked Questions
$divide divides one numeric expression by another inside aggregation pipelines. It takes two operands — a dividend (number being divided) and a divisor (number you divide by) — and returns the quotient.
The syntax is { $divide: [ <dividend>, <divisor> ] }. Each operand can be a field reference like "$revenue", a literal number, or another numeric expression.
If the divisor evaluates to zero, $divide throws an error. Use $cond to check for zero before dividing when your data may contain zero divisors.
Yes. A common pattern is { $divide: [ "$revenue", "$quantity" ] } to compute revenue per unit for each document.
If either the dividend or divisor is null, $divide returns null. It does not throw an error for null inputs.