Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

MongoDB $add Operator

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

MongoDB provides different types of arithmetic expression operators that are used in the aggregation pipeline stages and $add operator is one of them. This operator is used to add numbers or dates. If $add operator adds date, then it will treat other arguments as milliseconds and add to the specified date. 

Syntax: 

{ $add: [ <Expression1>, <Expression2>, ... <ExpressionN>] }

Here, the Expression must be a valid expression like numbers or 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.

Adding numbers using $add operator:

In this example, we are going to find the total salary of every employee in the development department. 

db.Employee.aggregate([{$match: {department: "Development"}},
... {$project: {name: 1, tSalary: {$add: 
                ["$firstSalary", "$secondSalary"]}}}])

Adding numbers in the embedded document using $add operator:

In this example, we are going to find a total of three months’ salary of the employee in the HR department. 

db.Employee.aggregate([{$match: {department: "HR"}},
... {$project: {name: 1, tSalary: {$add: ["$salary.firstMonth", 
                                          "$salary.secondMonth",
                                          "$salary.thirdMonth"]}}}])

Adding date using $add operator: 

In this example, we are going to extend the last date of the project by adding 5 days (i.e, 5*24*60*60000)  in the projectEndDate field of the testing department. 

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

My Personal Notes arrow_drop_up
Last Updated : 28 Jul, 2020
Like Article
Save Article
Similar Reads