$mod (Modulo)
Last updated: 2026-10-09
$mod (Modulo)
$mod returns the remainder of dividing two values in aggregation expressions. It takes two arguments — the dividend and the divisor — and returns the remainder after integer division. It is useful for paging, period detection, and parity checks, such as judging an order id odd or even with modulo 2, or sharding by timestamp modulo. A zero divisor returns null instead of throwing. The sign of the result follows the dividend. $mod works with integers and Decimals; be careful with floating-point values, converting to Decimal when needed.
| Category | Math |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $mod: [ <expression1>, <expression2> ] }
⚙️ Parameters
| dividend | A numeric value or an expression resolving to one. |
|---|---|
| divisor | The denominator expression; a zero divisor makes the result null. |
Returns:The remainder after division; null when the divisor is zero
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $mod: check whether the order number is odd
db.orders.aggregate([
{ $project: {
isOdd: { $eq: [{ $mod: ['$orderNo', 2] }, 1] }
} }
])
Output:
{ '_id': 1, 'isOdd': true }
{ '_id': 2, 'isOdd': false }
📌 Notes
- A zero divisor yields null without throwing
- The remainder takes the sign of the dividend, so -7 mod 3 gives -1
- Floating-point modulo can lose precision; convert to Decimal first
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhat happens when $mod divides by zero?
AIt returns null without throwing; use $ifNull for a default.
QHow is the sign of the $mod result determined?
AThe remainder follows the dividend, so -7 mod 3 is -1.
QCan $mod work with floating-point numbers?
ADecimals work, but plain doubles can be imprecise; convert to Decimal before taking the modulo.