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

CategoryMath
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $mod: [ <expression1>, <expression2> ] }

⚙️ Parameters

dividendA numeric value or an expression resolving to one.
divisorThe 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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏