MongoDB $abs Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $abs?

$abs is a MongoDB aggregation expression that returns the absolute value of a number—the magnitude without the sign. -10 becomes 10; 15 stays 15. Use it when you care about distance, not direction (refunds, temperature change, error size).

Remember
$abs = Math.abs for aggregation

{ $abs: <number expression> }

negative → positive
positive / zero → unchanged
null / missing → null
NaN → NaN

Common stages: $project, $addFields, $set
UsePrefer
Magnitude of a number or difference$abs
Subtract two numbers first$subtract then $abs
Round up / down after abs$ceil / $floor

How to Use $abs in MongoDB

One expression is enough—pass a field, a literal, or a nested math expression.

  1. Choose an expression stage ($project or $addFields).
  2. Pass a numeric expression to $abs (field path or nested operator).
  3. Name the output field (e.g. delta or absoluteAmount).
  4. For differences, nest $subtract inside $abs.
PieceRequired?Role
$absYesReturns absolute value of its argument
ExpressionYesNumber, "$field", or nested expression
StageYesUsually $project / $addFields / $set

Pseudocode

Pseudocode
for each document:
    value = evaluate(expression)
    if value is null or missing:
        result = null
    else if value is NaN:
        result = NaN
    else if value < 0:
        result = -value
    else:
        result = value
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while writing absolute-value expressions.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $abs: <expression> }
Difference pattern{ $abs: { $subtract: ["$a", "$b"] } }
null / missingReturns null
NaNReturns NaN
Sample check50→80 delta = 30; 90→70 delta = 20

Live Preview

Watch $abs turn signed temperature changes into magnitudes. Sample: 50→80, 40→40, 90→70, 60→70.

Simulates $abs: { $subtract: ["$startTemp", "$endTemp"] } (same idea as the mongosh examples below).

Result
_id 1: 50 − 80 = -30 → $abs → 30
_id 2: 40 − 40 = 0 → $abs → 0
_id 3: 90 − 70 = 20 → $abs → 20
_id 4: 60 − 70 = -10 → $abs → 10

[
  { _id: 1, delta: 30 },
  { _id: 2, delta: 0 },
  { _id: 3, delta: 20 },
  { _id: 4, delta: 10 }
]

Worked Walkthrough — Temperature Delta

One reading drops from 90 to 70. Subtraction alone can go negative; $abs keeps the change size.

Calculation
Document:
  { _id: 3, startTemp: 90, endTemp: 70 }

$subtract: [ "$startTemp", "$endTemp" ]
  90 - 70 → 20

$abs of that difference
  $abs(20) → 20

Another case (_id: 1):
  startTemp 50, endTemp 80
  50 - 80 → -30
  $abs(-30) → 30

Output field: delta = how far the temperature moved

MongoDB Examples

We use a tiny temperature collection for magnitude of change, then a transactions list for absolute amounts. Run these in mongosh after inserting each sample once.

Example 1 — Sample Data

Imagine four temperature readings. Each one has a start temperature and an end temperature. Some go up, some go down. We save them in a collection named temperatureChange.

mongosh
db.temperatureChange.insertMany([
  { _id: 1, startTemp: 50, endTemp: 80 },
  { _id: 2, startTemp: 40, endTemp: 40 },
  { _id: 3, startTemp: 90, endTemp: 70 },
  { _id: 4, startTemp: 60, endTemp: 70 }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps four documents in temperatureChange. Run find() to see them:

mongosh
db.temperatureChange.find().sort({ _id: 1 })

Read each document like this:

Field in MongoDBMeaningExample (_id 1)
_idDocument id (reading number)1
startTempTemperature at the start50
endTempTemperature at the end80
Picture
What each reading means:

  _id 1:  50 ──► 80   went up
  _id 2:  40 ──► 40   no change
  _id 3:  90 ──► 70   went down
  _id 4:  60 ──► 70   went up

Next lesson step (Example 2):
  how far did it move?  (ignore up vs down)

  _id 1: |50 − 80| = 30
  _id 2: |40 − 40| = 0
  _id 3: |90 − 70| = 20
  _id 4: |60 − 70| = 10

How It Works

  1. Insert once. insertMany adds four temperature documents to temperatureChange.
  2. MongoDB stores fields as written. Each document has _id, startTemp, and endTemp—plain numbers.
  3. find() shows the same shape. What you inserted is what you get back—ready for $abs in the next example.

Example 2 — Absolute Difference Between Two Fields

Goal: for each reading, report how far the temperature moved, ignoring whether it rose or fell.

mongosh
db.temperatureChange.aggregate([
  {
    $project: {
      delta: {
        $abs: {
          $subtract: ["$startTemp", "$endTemp"]
        }
      }
    }
  }
]);

How It Works

  1. Read the stored temps. MongoDB already has startTemp and endTemp from Example 1.
  2. Subtract first. $subtract: ["$startTemp", "$endTemp"] can be positive or negative (for _id 1: 50 − 80 = -30).
  3. Drop the sign. $abs turns -30 into 30 and leaves 20 as 20.
  4. Zero stays zero. When start equals end (_id 2), the difference is 0 and $abs returns 0.

Example 3 — Absolute Amount on a Field

Goal: treat refunds (negative amounts) as positive sizes. First we store three transactions, then we run $abs.

mongosh
db.transactions.insertMany([
  { _id: 1, amount: -10 },
  { _id: 2, amount: 15 },
  { _id: 3, amount: -20 }
]);

Check what MongoDB stored:

mongosh
db.transactions.find().sort({ _id: 1 })
mongosh
db.transactions.aggregate([
  {
    $project: {
      amount: 1,
      absoluteAmount: { $abs: "$amount" }
    }
  }
]);

How It Works

  1. Read the stored amounts. MongoDB already has -10, 15, and -20 in transactions.
  2. Flip negatives. $abs turns -10 → 10 and -20 → 20.
  3. Keep positives. 15 stays 15.
  4. Keep the original too. Projecting amount: 1 lets you compare signed vs absolute side by side.

Edge Cases & Pitfalls

Check these before using $abs in production pipelines.

null

Null and missing become null

If the field is missing or null, $abs returns null. Guard with $ifNull when you need a default of 0.

type

Argument must be numeric

Non-numeric types can error or yield unexpected results. Validate or convert first when data quality varies.

filter

Not a find() filter alone

$abs is an aggregation expression. Use it in $project / $addFields, or inside $expr if you need it in a query.

sign

You lose the sign on purpose

If direction matters (credit vs debit), keep the signed field too—do not replace it with only the absolute value.

Performance Notes

ApproachCostBest for
$abs on a fieldPer-document, cheapSimple magnitude fields
$abs + $subtractStill O(docs); two expressionsDistance between two fields
Store abs at write timeNo pipeline cost laterHot paths queried constantly

$abs is a lightweight math expression. Filter early with $match when you only need a subset of documents before projecting absolute values.

Key Takeaways

  • Role: absolute value (magnitude without sign) in aggregation.
  • Syntax: { $abs: <expression> } inside $project / $addFields.
  • Pattern: nest $subtract for absolute differences.
  • Null: missing or null input → null (not zero).

One line: $abs keeps the size of a number and drops the sign—ideal for distances, deltas, and magnitude reports.

Frequently Asked Questions

$abs returns the absolute value of a number. Negative values become positive; positive values and zero stay the same. Use it inside aggregation expression stages such as $project and $addFields.
Write { $abs: <expression> }. The expression can be a field path like "$amount", a literal number, or another numeric expression such as $subtract.
$abs returns null. It does not throw an error. If the argument is NaN, $abs returns NaN.
Inside expression stages: $project, $addFields, $set, and inside other expressions (for example nested in $group field expressions). It is not a query filter operator like $eq.
Combine $subtract with $abs: { $abs: { $subtract: [ "$a", "$b" ] } }. That gives how far apart two numbers are, ignoring which is larger.
Yes for numbers. Think of $abs as MongoDB’s aggregation version of Math.abs—run it in the pipeline, not as a find() filter by itself.

Next: $acos

Compute the inverse cosine of a number in an aggregation pipeline.

$acos tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful