$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:
- { $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:
- { "_id" : 1, "name" : "A", "hours" : 80, "resources" : 7 },
- { "_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:
- 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 }