$mod

  • $mod
  • Select documents where the value of a field divided by a divisor hasthe specified remainder (i.e. perform a modulo operation to selectdocuments). To specify a $mod expression, use the followingsyntax:
  1. { field: { $mod: [ divisor, remainder ] } }

Changed in version 2.6: The $mod operator errors when passed an array with feweror more elements. In previous versions, if passed an array withone element, the $mod operator uses 0 as theremainder value, and if passed an array with more than twoelements, the $mod ignores all but the first twoelements. Previous versions do return an error when passed anempty array. See Not Enough Elements Error andToo Many Elements Error for details.

Examples

Use $mod to Select Documents

Consider a collection inventory with the following documents:

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

Then, the following query selects those documents in theinventory collection where value of the qty field modulo4 equals 0:

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

The query returns the following documents:

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

Not Enough Elements Error

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

Array with Single Element

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

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

The statement results in the following error:

  1. error: {
  2. "$err" : "bad query: BadValue malformed mod, not enough elements",
  3. "code" : 16810
  4. }

Changed in version 2.6: In previous versions, if passed an array with one element, the$mod operator uses the specified element as the divisorand 0 as the remainder value.

Empty Array

The following operation incorrectly passes the $mod operatoran empty array:

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

The statement results in the following error:

  1. error: {
  2. "$err" : "bad query: BadValue malformed mod, not enough elements",
  3. "code" : 16810
  4. }

Changed in version 2.6: Previous versions returned the following error:

  1. error: { "$err" : "mod can't be 0", "code" : 10073 }

Too Many Elements Error

The $mod operator errors when passed an array with more thantwo elements.

For example, the following operation attempts to use the $modoperator with an array that contains four elements:

  1. error: {
  2. "$err" : "bad query: BadValue malformed mod, too many elements",
  3. "code" : 16810
  4. }

Changed in version 2.6: In previous versions, if passed an array with more than twoelements, the $mod ignores all but the first twoelements.