How to get absolute value in MongoDB

To get the absolute value we can use $abs operator. $abs are 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.

In the earlier 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 subtracting.


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

No comments:

Post a Comment

PostgreSQL-Query: Sort result set by specific field values using ORDER BY Clause

Problem: Suppose we have a book_inventory table which has some columns such as id, isbn, title, author, publisher, publish_date, etc.. whe...