Skip to content
Related Articles

Related Articles

MongoDB $subtract Operator
  • Last Updated : 01 Aug, 2020
GeeksforGeeks - Summer Carnival Banner

MongoDB provides different types of arithmetic expression operators that are used in the aggregation pipeline stages and an $subtract operator is one of them. This operator is used to subtract two numbers and return the difference in the numbers or to subtract two dates and return the difference in the milliseconds, or subtracts date and number in milliseconds and returns the date. 

Syntax: 

{ $subtract: [ <expression1>, <expression2> ] }

Here, the given arguments must be a valid expression like numbers or a date, and the second argument is subtracted from the first argument.  If you are subtracting a number from a date, then the first argument of this operator is a date.

 Examples:

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.

Using $subract operator subtract two numbers:

In this example, we are going to subtract the value of firstSalary field from the value of secondSalary field using $subtract operator.

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

Using $subract operator subtract two dates:

In this example, we are going to subtract two dates, i.e, the value of projectStartDate field from the value of projectEndDate field using a $subtract operator.

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

Using $subract operator subtracts milliseconds from a date:

In this example, we are going to subtract 5*24*60*60000 milliseconds (i.e., 5 days) from the value of projectEndDate field using a $subtract operator.

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :