$mod¶
On this page
-
$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
$modexpression, use the following syntax:Changed in version 2.6: The
$modoperator errors when passed an array with fewer or more elements. In previous versions, if passed an array with one element, the$modoperator uses0as the remainder value, and if passed an array with more than two elements, the$modignores all but the first two elements. Previous versions do return an error when passed an empty array. See Not Enough Elements Error and Too Many Elements Error for details.
Examples¶
Use $mod to Select Documents¶
Consider a collection inventory with the following documents:
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.
Array with Single Element¶
The following operation incorrectly passes the $mod operator
an array that contains a single element:
The statement results in the following error:
Changed in version 2.6: In previous versions, if passed an array with one element, the
$mod operator uses the specified element as the divisor
and 0 as the remainder value.
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:
Changed in version 2.6: In previous versions, if passed an array with more than two
elements, the $mod ignores all but the first two
elements.