MongoDB $divide Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $divide?

$divide is a MongoDB aggregation expression that divides one number by another and returns the quotient. Pass the dividend first and the divisor second.

Remember
$divide = dividend ÷ divisor

{ $divide: [ <dividend>, <divisor> ] }

$divide([80, 8]) → 10
$divide([40, 8]) → 5
$divide(["$hours", 8]) → workdays

divisor 0 → pipeline error
null operand → null
UsePrefer
Divide two numbers$divide
Multiply instead$multiply
Remainder after division$mod

How to Use $divide in MongoDB

Pass two numeric expressions in an array, then project or filter on the quotient.

  1. Choose an expression stage ($project or $addFields).
  2. Build { $divide: [ dividend, divisor ] } with fields or literals.
  3. Ensure the divisor is not zero (or guard with $cond).
  4. Optionally wrap with $ceil when you need whole units.
PieceRequired?Role
$divideYesDividend ÷ divisor → quotient
Two expressionsYesNumbers, fields, or nested math
Non-zero divisorYesZero makes the pipeline fail

Pseudocode

Pseudocode
for each document:
    a = evaluate(dividend)
    b = evaluate(divisor)
    if a is null or b is null (or missing):
        result = null
    else if b == 0:
        error  // aggregation fails
    else:
        result = a / b
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while writing division expressions.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $divide: [ <a>, <b> ] }
Meaninga ÷ b (order matters)
Workdays pattern$divide(["$hours", 8])
Per-unit pattern$divide(["$revenue", "$quantity"])
Zero divisorPipeline error
Null operandReturns null

Live Preview

Watch $divide turn total hours into workdays using an 8-hour day.

Simulates { $divide: ["$hours", 8] } (same idea as the mongosh examples below).

Result
hours = 80, dayLength = 8
$divide([hours, 8]) → 10

{ hours: 80, workdays: 10 }

Worked Walkthrough — Hours to Workdays

Eighty planning hours and an 8-hour workday. Division answers “how many full-day units is that?”

Calculation
Document:
  { city: "New York", hours: 80 }

workdays = hours ÷ 8
         = 80 ÷ 8
         = 10

$divide(["$hours", 8]) → 10

Argument order:
  [dividend, divisor]  →  hours first, 8 second
  not the other way around

MongoDB Examples

We store three city plans with hour totals, compute workdays (hours ÷ 8), then compute hours per task. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine a tiny planning collection. Each city has total hours and a task count.

mongosh
db.planning.insertMany([
  { _id: 1, city: "New York",  hours: 80, tasks: 7 },
  { _id: 2, city: "Singapore", hours: 40, tasks: 4 },
  { _id: 3, city: "Berlin",    hours: 24, tasks: 3 }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps three documents in planning. Run find() to see them:

mongosh
db.planning.find()

Read those documents like this:

Field in MongoDBValuePlain English
_id1 … 3Document id for this lesson
city"New York", "Singapore", "Berlin"Plan location
hours / tasksnumbersInputs we will divide
Picture
Expected workdays (hours ÷ 8):

  New York  80 ÷ 8 → 10
  Singapore 40 ÷ 8 → 5
  Berlin    24 ÷ 8 → 3

How It Works

  1. Insert once. insertMany adds three planning documents.
  2. Hours differ on purpose. You get clear quotients of 10, 5, and 3.
  3. find() shows the same shape. Ready for $divide next.

Example 2 — Hours ÷ 8

Goal: project each city with workdays using $divide(["$hours", 8]).

mongosh
db.planning.aggregate([
  {
    $project: {
      city: 1,
      workdays: { $divide: ["$hours", 8] },
      _id: 0
    }
  }
]);

How It Works

  1. Read hours. Left side is "$hours"; right side is the literal 8.
  2. Divide once per document. $divide returns 10, 5, and 3.
  3. Keep a short report. $project keeps city and adds workdays.
  4. Easy check. New York’s 80 hours is exactly ten 8-hour days.

Example 3 — Hours per Task

Same collection: divide two fields—hours by tasks—for an average load.

mongosh
db.planning.aggregate([
  {
    $project: {
      city: 1,
      hoursPerTask: { $divide: ["$hours", "$tasks"] },
      _id: 0
    }
  }
]);

How It Works

  1. Two field operands. Dividend is "$hours"; divisor is "$tasks".
  2. Singapore is exact. 40 ÷ 4 = 10.
  3. New York is fractional. 80 ÷ 7 ≈ 11.43 (a double).
  4. Need whole units? Wrap with $ceil when partial tasks still need a full block.

Edge Cases & Pitfalls

Check these before using $divide in production pipelines.

zero

Divide-by-zero fails the pipeline

A zero divisor is an error. Filter with $match or guard with $cond first.

order

Argument order matters

$divide([a, b]) is a ÷ b. Swapping sides flips the quotient.

null

Null operands return null

Missing or null dividend/divisor yields null, not an error. Handle that before averages or reports.

types

Operands must be numbers

Strings and other non-numeric types cause errors. Convert with $convert when needed.

Performance Notes

ApproachCostBest for
$divide alonePer-document arithmeticRatios and averages
+ $ceil / $roundStill O(docs)Whole-unit reporting
Guard with $condTiny branch costAvoiding divide-by-zero crashes

Division is cheap compared with large sorts or joins. Filter early with $match when only some documents need a ratio.

Key Takeaways

  • Role: dividend ÷ divisor → quotient.
  • Syntax: { $divide: [a, b] }.
  • Pattern: $divide(["$hours", 8]) for workdays.
  • Safety: never divide by zero—guard first.

One line: $divide answers “what is a divided by b?”—with dividend first, divisor second, and zero forbidden.

Frequently Asked Questions

$divide divides one number by another and returns the quotient. Pass two expressions in an array: dividend first, divisor second. Use it inside aggregation expression stages such as $project and $addFields.
The syntax is { $divide: [ <dividend>, <divisor> ] }. Each side can be a field reference, a literal number, or nested numeric math.
If the divisor is zero, the aggregation fails with an error. Guard with $cond, or filter out zero divisors with $match, before calling $divide.
If either the dividend or the divisor is null or missing, $divide returns null. It does not throw an error for null inputs.
Yes. $divide([a, b]) means a ÷ b. Swapping the arguments changes the result.
The default return type is a double. If at least one operand is a Decimal128, the result is a decimal.

Next: $eq

Compare two values for equality in an aggregation pipeline.

$eq tutorial →

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.

9 people found this page helpful