$mod
Performs a modulo operation and matches documents where the field value modulo divisor equals the specified remainder.
Syntax
{ <field>: { $mod: [<divisor>, <remainder>] } }
Parameters
field
stringrequiredThe numeric field to perform modulo operation on
divisor
numberrequiredThe number to divide by in the modulo operation
remainder
numberrequiredThe expected remainder value after the modulo operation
Examples
Find even numbers
Find stores where total sales is an even number
Query:
db.stores.find({ "sales.totalSales": { $mod: [2, 0] } })
Output:
Documents where totalSales is divisible by 2 (even numbers)
Find odd numbers
Find stores where staff count is an odd number
Query:
db.stores.find({ "staff.totalStaff.fullTime": { $mod: [2, 1] } })
Output:
Documents where fullTime staff count has remainder 1 when divided by 2 (odd numbers)
Pagination with modulo
Use modulo for pagination or sampling every nth document
Query:
db.stores.find({ "sales.totalSales": { $mod: [10, 5] } })
Output:
Documents where totalSales ends in 5 (remainder 5 when divided by 10)