MongoDB $divide Operator

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 4 Examples
Math

What You’ll Learn

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.

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.

📝 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)

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (arithmetic)
Syntax{ $divide: [ <dividend>, <divisor> ] }
OperandsTwo numeric expressions in an array
OutputQuotient (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

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:

mongosh
[
  { "_id": ObjectId("609c26812e9274a86871bc6a"), "revenue": 5000, "quantity": 10 },
  { "_id": ObjectId("609c26812e9274a86871bc6b"), "revenue": 7500, "quantity": 15 },
  { "_id": ObjectId("609c26812e9274a86871bc6c"), "revenue": 10000, "quantity": 20 }
]

Example 1 — Basic $divide on Fields

Use $project to add a new field called avgRevenuePerUnit:

mongosh
db.sales.aggregate([
  {
    $project: {
      avgRevenuePerUnit: {
        $divide: [ "$revenue", "$quantity" ]
      }
    }
  }
])

How It Works

  • Document 1: 5000 / 10 = 500
  • Document 2: 7500 / 15 = 500
  • Document 3: 10000 / 20 = 500

📈 Practical Patterns

Combine $divide with other operators for ratios, rates, and safe division in real pipelines.

Example 2 — Compute a Completion Ratio

Divide completed tasks by total tasks to get a progress ratio between 0 and 1:

mongosh
db.projects.aggregate([
  {
    $project: {
      name: 1,
      completed: 1,
      total: 1,
      completionRatio: {
        $divide: [ "$completed", "$total" ]
      }
    }
  }
])

How It Works

Multiply the ratio by 100 with $multiply if you need a percentage display value (e.g., 0.7 → 70).

Example 3 — Rate Per Hour with $addFields

Calculate an hourly rate by dividing total earnings by hours worked:

mongosh
db.timesheets.aggregate([
  {
    $addFields: {
      hourlyRate: {
        $divide: [ "$earnings", "$hoursWorked" ]
      }
    }
  }
])

How It Works

$addFields keeps all original fields and adds hourlyRate. This pattern works for any “total divided by count” metric.

Example 4 — Safe Division with $cond

Guard against divide-by-zero when the divisor might be 0:

mongosh
db.sales.aggregate([
  {
    $project: {
      avgRevenuePerUnit: {
        $cond: [
          { $eq: [ "$quantity", 0 ] },
          null,
          { $divide: [ "$revenue", "$quantity" ] }
        ]
      }
    }
  }
])

How It Works

If quantity is zero, return null instead of dividing. This prevents pipeline errors on documents with missing or zero quantities.

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

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.

💡 Best Practices

✅ Do

  • 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

Key Takeaways

Knowledge Unlocked

Five things to remember about $divide

Use these points when computing ratios in MongoDB pipelines.

5
Core concepts
📝 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.

Continue the Operator Series

Move on to $eq for equality comparisons, or review $degreesToRadians for angle conversion.

Next: $eq →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful