Docs Menu

Docs HomeMongoDB Manual

$mod (aggregation)

On this page

  • Definition
  • Example
$mod

Divides one number by another and returns the remainder.

The $mod expression has the following syntax:

{ $mod: [ <expression1>, <expression2> ] }

The first argument is the dividend, and the second argument is the divisor; i.e. first argument is divided by the second argument.

The arguments can be any valid expression as long as they resolve to numbers. For more information on expressions, see Expression Operators.

Starting in version 7.2, the output data type of the $mod operator is the larger of the two input data types.

Note

Prior to version 7.2, the value and field type of inputs determine the $mod output type if:

  • The divisor is of data type double but has an integral value.

  • The dividend is of data type int or long.

In this case, MongoDB converts the divisor to the dividend data type before it performs the mod operation and the output data type is the dividend data type.

Consider a conferencePlanning collection with the following documents:

db.conferencePlanning.insertMany( [
{ "_id" : 1, "city" : "New York", "hours" : 80, "tasks" : 7 },
{ "_id" : 2, "city" : "Singapore", "hours" : 40, "tasks" : 4 }
] )

The following aggregation uses the $mod expression to return the remainder of the hours field divided by the tasks field:

db.conferencePlanning.aggregate(
[
{ $project: { remainder: { $mod: [ "$hours", "$tasks" ] } } }
]
)

The operation returns the following results:

{ "_id" : 1, "remainder" : 3 }
{ "_id" : 2, "remainder" : 0 }
←  $minute (aggregation)$month (aggregation) →

On this page