Navigation
This version of the documentation is archived and no longer supported.

$abs (aggregation)

On this page

Definition

$abs

New in version 3.2.

Returns the absolute value of a number.

$abs has the following syntax:

{ $abs: <number> }

The <number> expression can be any valid expression as long as it resolves to a number. For more information on expressions, see Expressions.

Behavior

If the argument resolves to a value of null or refers to a field that is missing, $abs returns null. If the argument resolves to NaN, $abs returns NaN.

Example Results
{ $abs: -1 } 1
{ $abs: 1 } 1
{ $abs: null } null

Example

A collection ratings contains the following documents:

{ _id: 1, start: 5, end: 8 }
{ _id: 2, start: 4, end: 4 }
{ _id: 3, start: 9, end: 7 }
{ _id: 4, start: 6, end: 7 }

The following example calculates the magnitude of difference between the start and end ratings:

db.ratings.aggregate([
   {
     $project: { delta: { $abs: { $subtract: [ "$start", "$end" ] } } }
   }
])

The operation returns the following results:

{ "_id" : 1, "delta" : 3 }
{ "_id" : 2, "delta" : 0 }
{ "_id" : 3, "delta" : 2 }
{ "_id" : 4, "delta" : 1 }