MongoDB $abs

In MongoDB, the $abs aggregation pipeline operator returns the absolute value of a number.

Example

Suppose we have a collection called data with the following document:

{ "_id" : 1, "a" : 20, "b" : -20 }

We can use the $abs operator to return the absolute values of the a and b fields.

db.data.aggregate(
  [
    { $project: { 
        _id: 0,
        a: { $abs: [ "$a" ] },
        b: { $abs: [ "$b" ] }
      }
    }
  ]
)

Result:

{ "a" : 20, "b" : 20 }

Absolute values don’t have include any signs, and so we can see the negative sign has been removed from the b value.

You can think of an absolute value of a number as being the distance, on the number line, of that number from zero.

Null Values

Null values return null when using the $abs operator.

Suppose we add the following document to our collection:

{ "_id" : 2, "a" : 0, "b" : null }

Let’s run the the $abs operator against that document:

db.data.aggregate(
  [
    { $match: { _id: 2 } },
    { $project: { 
        _id: 0,
        a: { $abs: [ "$a" ] },
        b: { $abs: [ "$b" ] }
      }
    }
  ]
)

Result:

{ "a" : 0, "b" : null }

We can see that b resolved to null.

We can also see that 0 resolves to 0.

NaN Values

If the argument resolves to NaN$abs returns NaN.

Example:

db.data.aggregate(
  [
    { $match: { _id: 2 } },
    { $project: { 
        _id: 0,
        a: { $abs: [ "$a" ] },
        b: { $abs: [ 1 * "g" ] }
      }
    }
  ]
)

Result:

{ "a" : 0, "b" : NaN }

In this case I tried to multiple a number by a string, which resulted in NaN being returned.

Non-Existent Fields

If the $abs operator is applied against a field that doesn’t exist, null is returned.

Example:

db.data.aggregate(
  [
    { $match: { _id: 2 } },
    { $project: { 
        _id: 0,
        c: { $abs: [ "$c" ] }
      }
    }
  ]
)

Result:

{ "c" : null }

Combined With Other Operators

In this example I combine $abs with $subtract in order to calculate the magnitude of difference between fields a and b:

db.data.aggregate(
  [
    { $match: { _id: 1 } },
    { $project: { 
        _id: 0,
        a: 1,
        b: 1,
        result: { 
          $abs: { 
            $subtract: [ "$a", "$b" ] 
            }
        }
      }
    }
  ]
)

Result:

{ "a" : 20, "b" : -20, "result" : 40 }