$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.
| Category | Element & Evaluation |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ <field>: { $mod: [ <divisor>, <remainder> ] } }
⚙️ Parameters
| field | The numeric field to test. |
|---|---|
| divisor and remainder array | A 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
- The array is fixed as [divisor, remainder]; keep the order
- Integers only since 5.1; floats throw, negatives depend on modulo semantics
- Cannot use an index; for large data prefer the $mod aggregation expression
🏷️ Related Tags
💡 Related Cases
📚 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.