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

Please do not enter any spam link in the comment box.

Related Posts

What is the Use of isNaN Function in JavaScript? A Comprehensive Explanation for Effective Input Validation

In the world of JavaScript, input validation is a critical aspect of ensuring that user-provided data is processed correctly. One indispensa...