- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $subtract (aggregation)
$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, using the system
NOW
(available starting in 4.2) and returns the difference in
milliseconds:
Alternatively, you can use the Date()
for the current date:s
Both operations return documents that resemble the following: