$divide (aggregation)

Definition

  • $divide
  • Divides one number by another and returns the result. Pass thearguments to $divide in an array.

The $divide expression has the following syntax:

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

The first argument is the dividend, and the second argument is thedivisor; i.e. the 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.

Examples

Consider a planning collection with the following documents:

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

The following aggregation uses the $divide expression todivide the hours field by a literal 8 to compute the number ofwork days:

  1. db.planning.aggregate(
  2. [
  3. { $project: { name: 1, workdays: { $divide: [ "$hours", 8 ] } } }
  4. ]
  5. )

The operation returns the following results:

  1. { "_id" : 1, "name" : "A", "workdays" : 10 }
  2. { "_id" : 2, "name" : "B", "workdays" : 5 }