Get Absolute value with MongoDB aggregation framework?

To get absolute values in MongoDB aggregation framework, use the $abs operator within the $project stage. The $abs operator returns the absolute value of a number, converting negative numbers to positive while keeping positive numbers unchanged.

Syntax

db.collection.aggregate([
    {
        $project: {
            fieldName: { $abs: "$numberField" }
        }
    }
]);

Sample Data

Let us create a collection with positive, negative, and zero values ?

db.absoluteValueDemo.insertMany([
    { "Value": 98 },
    { "Value": -100 },
    { "Value": 0 },
    { "Value": -9999990 }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("..."),
        ObjectId("..."),
        ObjectId("..."),
        ObjectId("...")
    ]
}

Display the sample data ?

db.absoluteValueDemo.find();
{ "_id": ObjectId("5ca271f56304881c5ce84b9a"), "Value": 98 }
{ "_id": ObjectId("5ca271fa6304881c5ce84b9b"), "Value": -100 }
{ "_id": ObjectId("5ca271fe6304881c5ce84b9c"), "Value": 0 }
{ "_id": ObjectId("5ca2720f6304881c5ce84b9d"), "Value": -9999990 }

Example: Get Absolute Values

Use the $abs operator in the aggregation pipeline to calculate absolute values ?

db.absoluteValueDemo.aggregate([
    {
        $project: {
            AbsoluteValue: { $abs: "$Value" }
        }
    }
]);
{ "_id": ObjectId("5ca271f56304881c5ce84b9a"), "AbsoluteValue": 98 }
{ "_id": ObjectId("5ca271fa6304881c5ce84b9b"), "AbsoluteValue": 100 }
{ "_id": ObjectId("5ca271fe6304881c5ce84b9c"), "AbsoluteValue": 0 }
{ "_id": ObjectId("5ca2720f6304881c5ce84b9d"), "AbsoluteValue": 9999990 }

Key Points

  • The $abs operator works with integers, floats, and decimal numbers.
  • Returns the same value for positive numbers and zero.
  • Converts negative numbers to their positive equivalent.

Conclusion

The $abs operator in MongoDB aggregation framework efficiently calculates absolute values. Use it within $project stage to transform negative numbers to positive values while preserving the original positive numbers.

Updated on: 2026-03-15T00:43:46+05:30

310 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements