$abs (aggregation)

Definition

  • $abs

New in version 3.2.

Returns the absolute value of a number.

$abs has the following syntax:

  1. { $abs: <number> }

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

Behavior

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

ExampleResults
{ $abs: -1 }1
{ $abs: 1 }1
{ $abs: null }null

Example

A collection ratings contains the following documents:

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

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

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

The operation returns the following results:

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