Navigation

$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:

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

The $mod operator errors when passed an array with fewer or more than two elements. See Not Enough Elements Error and Too Many Elements Error for details.

Consider a collection inventory with the following documents:

{ "_id" : 1, "item" : "abc123", "qty" : 0 }
{ "_id" : 2, "item" : "xyz123", "qty" : 5 }
{ "_id" : 3, "item" : "ijk123", "qty" : 12 }

Then, the following query selects those documents in the inventory collection where value of the qty field modulo 4 equals 0:

db.inventory.find( { qty: { $mod: [ 4, 0 ] } } )

The query returns the following documents:

{ "_id" : 1, "item" : "abc123", "qty" : 0 }
{ "_id" : 3, "item" : "ijk123", "qty" : 12 }

The $mod operator errors when passed an array with fewer than two elements.

The following operation incorrectly passes the $mod operator an array that contains a single element:

db.inventory.find( { qty: { $mod: [ 4 ] } } )

The statement results in the following error:

error: {
"$err" : "bad query: BadValue malformed mod, not enough elements",
"code" : 16810
}

The following operation incorrectly passes the $mod operator an empty array:

db.inventory.find( { qty: { $mod: [ ] } } )

The statement results in the following error:

error: {
"$err" : "bad query: BadValue malformed mod, not enough elements",
"code" : 16810
}

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:

error: {
"$err" : "bad query: BadValue malformed mod, too many elements",
"code" : 16810
}
Give Feedback

On this page

  • Examples