The $subtract operator in MongoDB is an aggregation arithmetic operator used to subtract numbers and perform date/time calculations, helping transform fields in MongoDB queries.
Subtracts two numbers and returns the difference.
Subtracts two dates and returns the difference in milliseconds.
Subtracts milliseconds from a date and returns a new date.
Takes exactly two expressions: { $subtract: [expr1, expr2] }.
Second value is subtracted from the first.
Supports number–number, date–date (returns milliseconds), and date–number (subtracts milliseconds from date).
Syntax
{ $subtract: [ <expression1>, <expression2> ] }
$subtract: MongoDB aggregation operator for subtraction.
[ ... ]: Array containing exactly two values.
<expression1>: The base value (number or date).
<expression2>: The value to subtract from the first.
Type compatibility: Expressions must be compatible (numbers or dates).
Examples of MongoDB $subtract Operator
In the following examples, we are working with:
Database: GeeksforGeeks
Collection: Employee
Document: four documents that contain the details of the employees in the form of field-value pairs.