mongo-db
  1. mongo-db-abs-operator

$abs Operator - (MongoDB Misc)

The $abs operator is a mathematical operator in MongoDB that returns the absolute value of a given number. In this page, we will discuss how to use the $abs operator in MongoDB.

Syntax

The basic syntax of the $abs operator is as follows:

{ $abs: <number> }

Here, <number> is the numeric expression for which you want to calculate the absolute value.

Example

Suppose you have a collection named employee with the following documents:

{ "_id" : 1, "name" : "John Doe", "age" : -45 }
{ "_id" : 2, "name" : "Jane Doe", "age" : 25 }
{ "_id" : 3, "name" : "Bob Smith", "age" : -30 }

If you want to find the absolute age of all employees, you can use the $abs operator in your find() query as follows:

db.employee.find(
   {},
   { name: 1, age: 1, absoluteAge: { $abs: "$age" }}
)

This will return the following result:

{ "_id" : 1, "name" : "John Doe", "age" : -45, "absoluteAge" : 45 }
{ "_id" : 2, "name" : "Jane Doe", "age" : 25, "absoluteAge" : 25 }
{ "_id" : 3, "name" : "Bob Smith", "age" : -30, "absoluteAge" : 30 }

Here, the absoluteAge field contains the absolute value of the age field for each document.

Output

The $abs operator returns the absolute value of a given number.

Explanation

The $abs operator calculates the absolute value of a given number. If the number is positive, the function will return the value as it is. If the number is negative, the function will return the positive value of the number.

Use

The $abs operator can be useful when you need to convert negative values to positive values in your MongoDB queries. For example, you may want to find the absolute difference between two values or you may want to convert negative values to positive before performing other mathematical calculations on them.

Important Points

  • The $abs operator is a mathematical operator in MongoDB.
  • The operator returns the absolute value of a given number.
  • If the number is positive, the function will return the value as it is. If the number is negative, the function will return the positive value of the number.

Summary

In this page, we discussed the $abs operator in MongoDB. We covered the syntax, example, output, explanation, use, and important points of the operator. If you need to calculate the absolute value of a number in your MongoDB queries, you can use the $abs operator to do so.

Published on: