Aug 8, 2016

How to get absolute value in MongoDB

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

Before version of mongodb 3.2 we can’t use directly on 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 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 argument field is missing or null it will return null.

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

{$abs:null} result null