MongoDB $mod Operator

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

What Is $mod?

$mod is the modulo (remainder) operator. In aggregation it returns dividend % divisor. In queries it filters documents where a field’s remainder matches a value you choose—handy for “divisible by” and odd/even checks.

Remember
$mod = remainder after division

Aggregation (compute):
  { $mod: [ <dividend>, <divisor> ] }
  $mod([80, 7]) → 3

Query (filter):
  { field: { $mod: [ <divisor>, <remainder> ] } }
  { qty: { $mod: [4, 0] } } → qty % 4 === 0

divisor 0 → error
negative dividend → negative remainder
UsePrefer
Compute a remainderAggregation $mod
Filter by remainderQuery $mod (or $expr)
Quotient (not remainder)$divide

How to Use $mod in MongoDB

Pick compute (aggregation) or filter (query)—argument order differs.

  1. To compute: use $addFields / $project with { $mod: [dividend, divisor] }.
  2. To filter: use find() or $match with { field: { $mod: [divisor, remainder] } }.
  3. Keep the divisor non-zero.
  4. Remember: query array is not the same order as aggregation.
ContextArray orderResult
Aggregation[dividend, divisor]Returns the remainder
Query / $match[divisor, remainder]Keeps matching documents

Pseudocode

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

// Query — filter
keep document if (field % divisor) == remainder

Cheat Sheet

Keep these facts handy while writing modulo expressions.

TopicDetail
Agg syntax{ $mod: [ <a>, <b> ] } → a % b
Query syntax{ f: { $mod: [ <b>, <r> ] } } → f % b === r
Sample80 % 7 = 3, 40 % 4 = 0
Even check{ n: { $mod: [2, 0] } }
Odd check{ n: { $mod: [2, 1] } }
Divide by zeroPipeline / query error
Negative dividendRemainder is negative

Live Preview

Watch aggregation $mod compute a remainder. Pick a pair, then run.

Simulates aggregation { $mod: [dividend, divisor] } (same idea as the mongosh examples below).

Result
$mod([80, 7])
80 ÷ 7 = 11 remainder 3

{ remainder: 3 }

Worked Walkthrough — Hours ÷ Tasks

A conference city has 80 hours and 7 tasks. What is left after splitting hours evenly across tasks?

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

80 ÷ 7 = 11 full groups
11 × 7 = 77
remainder = 80 − 77 = 3

$mod(["$hours", "$tasks"]) → 3

Singapore: 40 % 4 = 0 (exact fit) ✓

MongoDB Examples

We use a small conferencePlanning collection for aggregation, then an inventory query filter. Run these in mongosh.

Example 1 — Sample Data

Imagine two cities planning a conference. Each has total hours and a task count. We save them in conferencePlanning.

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

How the Data Is Stored in MongoDB

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

mongosh
db.conferencePlanning.find()

Read one document like this:

Field in MongoDBValue (NY)Plain English
city"New York"Location name
hours80Dividend (total hours)
tasks7Divisor (task count)

How It Works

  1. Insert once. insertMany adds two planning documents.
  2. Two numbers per city. hours and tasks are ready for $mod.
  3. find() shows the same shape. What you inserted is what you get back.

Example 2 — Aggregation Remainder

Goal: compute hours % tasks for each city with aggregation $mod.

mongosh
db.conferencePlanning.aggregate([
  {
    $project: {
      city: 1,
      remainder: { $mod: ["$hours", "$tasks"] }
    }
  }
]);

How It Works

  1. Array order is [dividend, divisor]. ["$hours", "$tasks"] means hours ÷ tasks.
  2. New York. 80 % 7 = 3 leftover hours.
  3. Singapore. 40 % 4 = 0—hours divide evenly.
  4. $project keeps listed fields (plus _id) and adds remainder.

Example 3 — Query Filter

Different context: filter inventory where quantity is divisible by 4. Query $mod uses [divisor, remainder].

mongosh
db.inventory.insertMany([
  { _id: 1, item: "abc123", qty: 0 },
  { _id: 2, item: "xyz123", qty: 5 },
  { _id: 3, item: "ijk123", qty: 12 }
]);

db.inventory.find({ qty: { $mod: [4, 0] } });

How It Works

  1. Field is the dividend. MongoDB tests qty % 4.
  2. Array is [divisor, remainder]. [4, 0] means “remainder must be 0”.
  3. Matches. 0 % 4 = 0 and 12 % 4 = 0.
  4. Skipped. 5 % 4 = 1, so item 2 is not returned.

Edge Cases & Pitfalls

Check these before using $mod in production pipelines.

order

Don’t mix argument orders

Aggregation is [dividend, divisor]. Query is [divisor, remainder]. Swapping them silently gives wrong results.

zero

Divisor must not be zero

A zero divisor errors. Guard with $cond or filter bad rows first.

sign

Negative dividends stay negative

-13 % 9 is -4, not 5. Plan for the sign if you store negatives.

null

Null inputs return null (aggregation)

If either argument is null or missing in aggregation, $mod returns null.

Performance Notes

ApproachCostBest for
Agg $modPer-document mathComputed remainders / reports
Query $modUsually collection scanOdd/even or divisible filters
Precompute + indexFaster readsHot remainder filters

Query $mod rarely uses a standard index efficiently. For frequent filters, store a helper field (for example qtyMod4) and index that, or narrow with $match on other fields first.

Key Takeaways

  • Agg: $mod([a, b]) → a % b.
  • Query: { f: { $mod: [b, r] } } → f % b === r.
  • Order differs between compute and filter.
  • Never divide by zero.

One line: $mod answers “what is left after division?”—or “keep rows with this remainder.”

Frequently Asked Questions

In aggregation, $mod divides one number by another and returns the remainder (like % in JavaScript). In find() / $match queries, $mod filters documents where a field’s remainder equals a value you specify.
Use { $mod: [ <dividend>, <divisor> ] }. Example: { $mod: [ "$hours", "$tasks" ] } returns hours % tasks.
Use { field: { $mod: [ <divisor>, <remainder> ] } }. Example: { qty: { $mod: [ 4, 0 ] } } matches documents where qty % 4 === 0. The field is the dividend.
Aggregation $mod computes a value: [dividend, divisor]. Query $mod filters: [divisor, expected remainder] against the field. Check which context you are in before writing the array.
In aggregation, a zero divisor makes the pipeline fail. In queries, a zero divisor is invalid. Always use a non-zero divisor.
When the dividend is negative, the remainder is also negative (JavaScript-style). Example: $mod([-13, 9]) returns -4.

Next: $month

Extract the 1–12 month portion of a date in aggregation.

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