MongoDB $abs operator (original) (raw)

Last Updated : 15 Apr, 2026

The $abs operator returns the absolute value of a number in MongoDB aggregation pipeline, converting negative values to positive for clean and consistent calculations.

Syntax

{ $abs: }

Features of the MongoDB $abs Operator

Examples of MongoDB $abs operator

In the following examples, we will work with the GeeksforGeeks database and the Employee collection.

Screenshot-2026-02-11-115630

Example 1: Using $abs to Ensure Non-Negative Salary Values

Total salary of every employee in the development department, ensuring that we only use positive values (by taking the absolute value).

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

**Output:

abs

Example 2: Using $abs operator in embedded documents

Total of three months' salary of the employee in the HR department, where the salary is stored in an embedded document, and ensure that the result is non-negative.

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

**Output:

abs2