Skip to main content

How to get absolute value in MongoDB

To get the absolute value we can use $abs operator. $abs is the arithmetic aggregate operator which returns the absolute value of the number.
Absolute value means it always returns positive value while the number may positive or negative.

Before version of MongoDB 3.2, we can’t use directly on the number like below.

{ $project: { number: { $abs: '$number } }  

We needed some calculation as below.

db.Col.aggregate([
   {
     $project: { abs_value: { $abs: { $subtract: [ 1, 2 ] } } }
   }]).
Syntax:


{ $abs: <number> }


Example: Run the following script which $subtract will return negative value but $abs will return the absolute value of subtract.


db.Col.aggregate([
   {
     $project: { abs_value: { $abs: { $subtract: [ 1, 2 ] } } }
   }
])


OR


db.ratings.aggregate([
   {
     $project: { abs_value: { $abs: -1 } }
   }
])


It will return abs_value =1.0

Note: If the argument field is missing or null it will return null.

{$abs:-1} result 1
{$abs:1} result 1


{$abs:null} result null