MongoDB $subtract Operator (original) (raw)

Last Updated : 15 Apr, 2026

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.

Syntax

{ $subtract: [ , ] }

Examples of MongoDB $subtract Operator

In the following examples, we are working with:

Screenshot-2026-02-10-180010

Example 1: Subtract Numbers

Subtract the value of firstSalary field from the value of secondSalary field using $subtract operator.

**Query:

db.Employee.aggregate([
{ $match: { department: "Development" } },
{
$project: {
result: { subtract:["subtract: ["subtract:["secondSalary", "$firstSalary"] }
}
}
])

**Output:

ab

Example 2: Subtract Two Dates

Subtract two dates, i.e, the value of projectStartDate field from the value of projectEndDate field using a $subtract operator.

**Query:

db.Employee.aggregate([
{ $match: { department: "Testing" } },
{
$project: {
diffResult: { subtract:["subtract: ["subtract:["projectEndDate", "$projectStartDate"] }
}
}
])

**Output:

subtract

Example 3: Subtract Milliseconds from a Date

Subtract 5*24*60*60000 milliseconds (i.e., 5 days) from the value of projectEndDate field using a $subtract operator.

**Query:

db.Employee.aggregate([
{ $match: { department: "Testing" } },
{ $project: {
newprojectEndDate: {
subtract:["subtract: ["subtract:["projectEndDate", 5 * 24 * 60 * 60000]
}
}
}
])

**Output:

subtractTwo

Use Cases of MongoDB $subtract Operator

The $subtract operator is useful for various scenarios, including: