MongoDB $abs Operator

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 4 Examples
Aggregation

What You’ll Learn

The $abs operator returns the absolute value of a number in MongoDB aggregation pipelines. It is a simple math operator that turns negative values into positive ones while leaving positive values unchanged.

01

Absolute Value

Convert negatives to positives.

02

Syntax

One expression inside $abs.

03

$project Stage

Add computed fields easily.

04

Field References

Work on document fields.

05

Use Cases

Finance, normalization, QA.

06

Null Safety

Know how null inputs behave.

Definition and Usage

In MongoDB’s aggregation framework, the $abs operator computes the absolute value of a numeric expression. For example, -10 becomes 10, and 15 stays 15. This is useful when you care about magnitude rather than sign — such as transaction amounts, price differences, or error distances.

💡
Beginner Tip

Think of $abs as MongoDB’s version of JavaScript’s Math.abs(). Use it inside aggregation expression stages, not as a standalone query filter operator.

📝 Syntax

The $abs operator takes one numeric expression:

mongosh
{ $abs: <expression> }

Syntax Rules

  • $abs — returns the absolute value of the expression that follows.
  • <expression> — can be a field path ("$amount"), a literal number, or another numeric expression.
  • Use it inside stages like $project, $addFields, or $set.
  • If the input is null, the result is null.

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator
Syntax{ $abs: <expression> }
InputNumber or numeric expression
OutputNon-negative number (or null)
Common stages$project, $addFields, $set
Example
{
  $abs: -20
}

Returns 20

Field
{
  $abs: "$amount"
}

Absolute field value

Null input
{
  $abs: null
}

Returns null

Zero
{
  $abs: 0
}

Returns 0

Examples Gallery

Walk through sample data, an aggregation pipeline, and the output step by step.

📚 Transaction Amounts

Start with a simple transactions collection and compute absolute amounts with $project.

Sample Input Documents

Suppose you have a transactions collection with an amount field. Some amounts are negative (refunds or debits):

mongosh
[
  { "_id": ObjectId("609c26812e9274a86871bc6a"), "amount": -10 },
  { "_id": ObjectId("609c26812e9274a86871bc6b"), "amount": 15 },
  { "_id": ObjectId("609c26812e9274a86871bc6c"), "amount": -20 }
]

Example 1 — Basic $abs on a Field

Use $project to add a new field called absoluteAmount:

mongosh
db.transactions.aggregate([
  {
    $project: {
      absoluteAmount: { $abs: "$amount" }
    }
  }
])

How It Works

  • Document 1: amount is -10, so absoluteAmount becomes 10.
  • Document 2: amount is already 15, so it stays 15.
  • Document 3: amount is -20, so absoluteAmount becomes 20.

📈 Practical Patterns

Combine $abs with other operators for real reporting and data-cleaning tasks.

Example 2 — Absolute Difference Between Two Fields

When comparing expected and actual values, the sign of the difference may not matter — only how far off you are:

mongosh
db.inventory.aggregate([
  {
    $project: {
      item: 1,
      expected: 1,
      actual: 1,
      variance: {
        $abs: { $subtract: [ "$actual", "$expected" ] }
      }
    }
  }
])

How It Works

$subtract finds the signed difference. $abs removes the sign so both overages and shortages are measured as positive distances.

Example 3 — Normalize Signed Values with $addFields

Add a normalized field without changing the original signed value:

mongosh
db.ledger.aggregate([
  {
    $addFields: {
      normalizedAmount: { $abs: "$amount" },
      direction: {
        $cond: [
          { $gte: [ "$amount", 0 ] },
          "credit",
          "debit"
        ]
      }
    }
  }
])

How It Works

Keep the original signed amount for accounting, but use normalizedAmount when you need totals, charts, or comparisons based on magnitude.

Example 4 — $abs with a Literal Expression

You can pass a literal number or nested expression directly:

mongosh
db.samples.aggregate([
  {
    $project: {
      fromLiteral: { $abs: -42 },
      fromMultiply: { $abs: { $multiply: [ "$score", -1 ] } }
    }
  }
])

How It Works

{ $abs: -42 } always returns 42. When applied to an expression like { $multiply: [ "$score", -1 ] }, it flips the sign of the computed result.

🚀 Use Cases

  • Data normalization — convert negative values to positive ones for consistent reporting.
  • Financial analysis — measure transaction magnitude regardless of debit or credit direction.
  • Error handling and QA — compare expected vs actual values using absolute deviation.
  • Analytics dashboards — sum or average magnitudes without sign cancelling out results incorrectly.

🧠 How $abs Works

1

MongoDB reads the expression

The pipeline evaluates the input — a field like "$amount" or a numeric expression.

Input
2

$abs removes the sign

Negative numbers become positive. Positive numbers and zero stay unchanged.

Transform
3

The result is stored in the pipeline

The computed value is written to the field you define in $project or $addFields.

Output
=

Clean numeric data

You get magnitude-based values ready for charts, totals, and comparisons.

Conclusion

The $abs operator is a small but essential tool in MongoDB aggregation pipelines. It lets you work with numeric magnitude instead of sign, which is especially helpful for financial data, inventory variance, and data normalization tasks.

For beginners, the key idea is simple: wrap any numeric expression in { $abs: ... } inside a stage like $project, and MongoDB returns the non-negative result.

💡 Best Practices

✅ Do

  • Use $abs when magnitude matters more than sign
  • Combine it with $subtract for variance calculations
  • Keep original signed fields when direction still matters
  • Handle null inputs with $ifNull when needed
  • Test with negative, positive, and zero values

❌ Don’t

  • Use $abs as a query filter operator outside expressions
  • Assume it converts non-numeric strings to numbers
  • Replace signed accounting fields when you still need debit/credit info
  • Forget that null input returns null
  • Apply it before validating that the field is numeric

Key Takeaways

Knowledge Unlocked

Five things to remember about $abs

Use these points when writing your next aggregation pipeline.

5
Core concepts
📝 02

Simple Syntax

{ $abs: expr }

Syntax
🛠 03

Pipeline Stages

$project, $addFields, $set.

Usage
💰 04

Finance Ready

Great for transaction data.

Use case
05

Null Aware

null in → null out.

Edge case

❓ Frequently Asked Questions

$abs returns the absolute value of a number. Negative values become positive, and positive values stay the same. It is an aggregation expression operator used inside stages like $project and $addFields.
The syntax is { $abs: <expression> }. The expression can be a field reference like "$amount", a literal number, or another numeric expression.
Yes. That is its main purpose. For example, $abs applied to -20 returns 20.
$abs returns null when the input is null. It does not throw an error.
Use $abs inside expression stages such as $project, $addFields, $set, and $group accumulators when you need a non-negative numeric result.

Explore More MongoDB Operators

Continue with $acos, $round, and other aggregation pipeline operators.

Next: $acos →

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.

5 people found this page helpful