$mod¶
-
$mod
¶ Select documents where the value of a field divided by a divisor has the specified remainder (i.e. perform a modulo operation to select documents). To specify a
$mod
expression, use the following syntax:
Behavior¶
The $mod
operator returns an error if the [ divisor,
remainder ]
array contains fewer or more than two elements. For
examples, see Not Enough Elements Error and
Too Many Elements Error respectively.
Also, starting in MongoDB 5.1 (and 5.0.4 and 4.4.10), $mod
returns an error if the divisor
or remainder
values evaluate to:
NaN
(not a number) orInfinity
.- A value that cannot be represented using a 64-bit integer.
Examples¶
Use $mod
to Select Documents¶
Create an inventory
collection:
Then, the following query selects those documents in the
inventory
collection where value of the qty
field modulo
4
equals 0
:
The query returns the following documents:
Not Enough Elements Error¶
The $mod
operator errors when passed an array with fewer than
two elements.
Too Many Elements Error¶
The $mod
operator errors when passed an array with more than
two elements.
For example, the following operation attempts to use the $mod
operator with an array that contains four elements:
The statement results in the following error:
Floating Point Arguments¶
The $mod
expression rounds decimal input towards zero.
The following examples demonstrate this behavior:
Example
Input query:
Results:
Example
Input query:
Results:
Example
Input query:
Results:
Each query applies 4
to the $mod
expression regardless of
decimal points, resulting in the same result set.