$mod (aggregation)

Definition

  • $mod
  • Divides one number by another and returns the remainder.

The $mod expression has the following syntax:

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

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

The arguments can be any valid expression as long as they resolve to numbers. Formore information on expressions, see Expressions.

Example

Consider a planning collection with the following documents:

  1. { "_id" : 1, "project" : "A", "hours" : 80, "tasks" : 7 }
  2. { "_id" : 2, "project" : "B", "hours" : 40, "tasks" : 4 }

The following aggregation uses the $mod expression toreturn the remainder of the hours field divided by the tasksfield:

  1. db.planning.aggregate(
  2. [
  3. { $project: { remainder: { $mod: [ "$hours", "$tasks" ] } } }
  4. ]
  5. )

The operation returns the following results:

  1. { "_id" : 1, "remainder" : 3 }
  2. { "_id" : 2, "remainder" : 0 }