$mod (Modulo)

Last updated: 2026-10-09

$mod (Modulo)

$mod matches documents where the field value divided by a divisor leaves a specified remainder. `{ qty: { $mod: [4, 0] } }` matches quantities divisible by 4. Common for bucketing and periodic filters. Since MongoDB 5.1 both the divisor and remainder must be integers; floating-point values throw an error.

CategoryElement & Evaluation
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

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

⚙️ Parameters

fieldThe numeric field to test.
divisor and remainder arrayA fixed [divisor, remainder] pair of integers.

Returns:Cursor of matching documents

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// $mod: quantities divisible by 4
db.products.find({ qty: { $mod: [4, 0] } })

// Remainder 1: first item of each group of 4
db.products.find({ qty: { $mod: [4, 1] } })

Output:

// Returns quantities with remainder 0 (divisible); the second query returns remainder 1

📌 Notes

📚 Related Tutorials

❓ FAQ

QWhat do the two numbers in $mod mean?
A[divisor, remainder]; matches values whose division remainder equals the second number.
QDoes $mod support floats?
ANot since MongoDB 5.1 — divisor and remainder must be integers.
QCan $mod use an index?
ANo, it is a computed predicate and scans the collection.
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%

🙏 帮我们做得更好

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

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