Fix This Page
Navigation

$divide (aggregation)

On this page

Definition

$divide

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

The $divide expression has the following syntax:

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

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

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

Examples

Consider a planning collection with the following documents:

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

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

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

The operation returns the following results:

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