MongoDB $mod Operator

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 4 Examples
Math & Query

What You’ll Learn

The $mod operator performs modulo (remainder) math in MongoDB. It appears in two forms: as a query filter in find() and $match, and as an aggregation expression that computes remainders inside pipelines.

01

Remainder Math

dividend % divisor.

02

Two Forms

Query vs aggregation.

03

Divisibility

Filter multiples of N.

04

Odd / Even

Parity checks.

05

Use Cases

Buckets, sampling.

06

Argument Order

Context matters.

Definition and Usage

Modulo returns the remainder after division. For example, 10 % 3 = 1, 15 % 3 = 0, and 20 % 3 = 2. MongoDB’s $mod lets you apply this logic to stored numeric fields.

In an aggregation expression, { $mod: [ dividend, divisor ] } computes and returns the remainder. In a query, { field: { $mod: [ divisor, remainder ] } } matches documents where field % divisor == remainder.

💡
Beginner Tip

The argument order differs between query and aggregation $mod. In queries, the second value is the expected remainder. In aggregation, the second value is the divisor you divide by.

📝 Syntax

MongoDB uses $mod in two contexts. Learn both:

Aggregation Expression (returns remainder)

mongosh
{ $mod: [ <dividend>, <divisor> ] }

Query Operator (filters documents)

mongosh
{ <field>: { $mod: [ <divisor>, <remainder> ] } }

Syntax Rules

  • Aggregation[dividend, divisor]; returns the computed remainder.
  • Query[divisor, remainder]; matches when field % divisor == remainder.
  • Operands — can be field paths, literals, or numeric expressions.
  • Divisor zero — causes an error; always use a non-zero divisor.
  • Null input — aggregation $mod returns null if either operand is null.

💡 Query $mod vs Aggregation $mod

Query{ value: { $mod: [ 3, 0 ] } } → matches where value is divisible by 3
Aggregation{ $mod: [ "$value", 3 ] } → returns remainder (10→1, 15→0, 20→2)
Do not swap the argument order — they mean different things in each context

⚡ Quick Reference

QuestionAnswer
Operator typeQuery operator and aggregation expression operator
Aggregation syntax{ $mod: [ dividend, divisor ] }
Query syntax{ field: { $mod: [ divisor, remainder ] } }
Return type (aggregation)Integer remainder (or null)
Common usesDivisibility filters, odd/even, bucketing
Compute remainder
{ $mod: [ "$value", 3 ] }

Aggregation expression

Divisible by 3
{
  value: { $mod: [ 3, 0 ] }
}

Query filter

Even numbers
{
  value: { $mod: [ 2, 0 ] }
}

remainder 0

In $project
{
  remainder: {
    $mod: [ "$value", 5 ]
  }
}

Add computed field

Examples Gallery

Compute remainders in aggregation, filter divisible values in queries, check odd/even parity, and assign buckets with $mod.

📚 Numbers Collection

Start with a numbers collection and explore both aggregation and query forms of $mod.

Sample Input Documents

Suppose you have a numbers collection:

mongosh
[
  { "_id": ObjectId("609c26812e9274a86871bc6a"), "value": 10 },
  { "_id": ObjectId("609c26812e9274a86871bc6b"), "value": 15 },
  { "_id": ObjectId("609c26812e9274a86871bc6c"), "value": 20 }
]

Example 1 — Compute Remainder in Aggregation

Use aggregation $mod to add a remainder field (divide each value by 3):

mongosh
db.numbers.aggregate([
  {
    $project: {
      value: 1,
      remainder: { $mod: [ "$value", 3 ] }
    }
  }
])

How It Works

  • 10 % 3 = 1
  • 15 % 3 = 0 (divisible by 3)
  • 20 % 3 = 2

📈 Practical Patterns

Query filters, parity checks, and bucket assignment.

Example 2 — Filter Values Divisible by 3 (Query $mod)

Find documents where value is a multiple of 3 using query syntax:

mongosh
db.numbers.find({
  value: { $mod: [ 3, 0 ] }
})

How It Works

Query $mod uses [divisor, remainder]. Here [3, 0] means “match when value % 3 == 0.” Only 15 qualifies; 10 and 20 are filtered out.

Example 3 — Find Even Numbers with $expr

In aggregation $match, use expression $mod with $eq:

mongosh
db.numbers.aggregate([
  {
    $match: {
      $expr: {
        $eq: [
          { $mod: [ "$value", 2 ] },
          0
        ]
      }
    }
  }
])

How It Works

Inside $expr, aggregation $mod computes value % 2. When the result equals 0, the number is even. This pattern works for any parity or divisibility check in pipelines.

Example 4 — Assign Buckets for Sampling

Split records into 4 buckets using modulo for round-robin sampling:

mongosh
db.users.aggregate([
  {
    $project: {
      name: 1,
      userId: 1,
      bucket: { $mod: [ "$userId", 4 ] }
    }
  }
])

How It Works

$mod maps each userId to bucket 0, 1, 2, or 3. You can then process one bucket per job run, spread load across workers, or sample a subset evenly.

Bonus — Label Odd or Even with $cond

Add a readable parity label using $mod and $cond:

mongosh
db.numbers.aggregate([
  {
    $project: {
      value: 1,
      parity: {
        $cond: {
          if: {
            $eq: [
              { $mod: [ "$value", 2 ] },
              0
            ]
          },
          then: "even",
          else: "odd"
        }
      }
    }
  }
])

How It Works

10 and 20 become "even"; 15 becomes "odd". Combine $mod with $cond whenever you need categorical labels from numeric rules.

🚀 Use Cases

  • Divisibility filters — find records divisible by N (multiples of 5, 10, etc.).
  • Odd/even checks — parity logic for alternating workflows or A/B splits.
  • Data bucketing — assign IDs to buckets for sampling, sharding, or batch jobs.
  • Periodic patterns — group or filter cyclical numeric data (every 7th record, etc.).

🧠 How $mod Works

1

MongoDB reads the operands

Fields or literals are evaluated per document. Check whether you are in query or aggregation context.

Input
2

$mod applies modulo

Aggregation returns dividend % divisor. Query compares field % divisor to the expected remainder.

Compute
3

Result or match

Aggregation stores the remainder in a new field. Query includes or excludes documents based on the match.

Output
=

Remainder-based logic

Use for divisibility, parity, bucketing, and cyclic data patterns across queries and pipelines.

Conclusion

The $mod operator brings modulo arithmetic to MongoDB queries and aggregation pipelines. Use the query form to filter by divisibility, and the aggregation form to compute remainders as new fields.

The most common beginner mistake is swapping the argument order. Remember: query uses [divisor, remainder], aggregation uses [dividend, divisor]. Next in the series: $month.

💡 Best Practices

✅ Do

  • Check whether you need query $mod or aggregation $mod
  • Use query { $mod: [ N, 0 ] } for “divisible by N” filters
  • Combine aggregation $mod with $eq inside $expr
  • Guard against zero divisors in dynamic pipelines
  • Test with edge values: 0, negatives, and large numbers

❌ Don’t

  • Swap argument order between query and aggregation forms
  • Use aggregation syntax directly in a plain find() filter
  • Divide by zero — it throws an error
  • Assume $mod works on non-numeric strings
  • Confuse query $mod with JavaScript’s % operator syntax

Key Takeaways

Knowledge Unlocked

Five things to remember about $mod

Use these points when working with modulo logic in MongoDB.

5
Core concepts
📝 02

Two Forms

Query vs aggregation.

Syntax
🛠 03

Argument Order

Differs by context.

Critical
📊 04

Divisibility

[N, 0] in queries.

Use case
05

No Zero Divisor

Throws an error.

Edge case

❓ Frequently Asked Questions

$mod performs a modulo (remainder) operation. In aggregation expressions it returns dividend % divisor. In find() and $match queries it filters documents where a field's remainder matches a given value.
Aggregation expression: { $mod: [ <dividend>, <divisor> ] }. Example: { $mod: [ "$value", 3 ] } returns the remainder when value is divided by 3.
Query operator: { field: { $mod: [ <divisor>, <remainder> ] } }. Example: { value: { $mod: [ 3, 0 ] } } matches documents where value is divisible by 3.
Query $mod is a filter: [divisor, expected remainder]. Aggregation $mod is a math expression: [dividend, divisor] that computes and returns the remainder. Always check which context you are in.
In aggregation, if the divisor is zero, $mod throws an error. In queries, a zero divisor is invalid. Always ensure the divisor is non-zero.

Continue the Operator Series

Move on to $month for date extraction, or review $divide for division in pipelines.

Next: $month →

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