$subtract (aggregation)
On this page
Definition
-
$subtract
-
Subtracts two numbers to return the difference, or two dates to return the difference in milliseconds, or a date and a number in milliseconds to return the resulting date.
The
$subtract
expression has the following syntax:The second argument is subtracted from the first argument.
The arguments can be any valid expression as long as they resolve to numbers and/or dates. To subtract a number from a date, the date must be the first argument. For more information on expressions, see Expressions.
Examples
Consider a sales
collection with the following documents:
Subtract Numbers
The following aggregation uses the $subtract
expression to compute the total
by subtracting the discount
from the subtotal of price
and fee
.
The operation returns the following results:
Subtract Two Dates
The following aggregation uses the $subtract
expression to subtract $date
from the current date and returns the difference in milliseconds:
The operation returns the following results:
Subtract Milliseconds from a Date
The following aggregation uses the $subtract
expression to subtract 5 * 60 * 1000 milliseconds (5 minutes) from the “$date” field:
The operation returns the following results: