$abs (Absolute Value)
Last updated: 2026-10-09
$abs (Absolute Value)
$abs returns the absolute value of a single numeric expression. It is commonly used to compute distances, deviations, or errors, such as how far an actual value is from a target, or a geographic offset. A null or missing argument yields null; positive infinity stays positive infinity, and negative numbers become positive. Combined with $sign it gives both the magnitude and the sign of a number. $abs supports integers, doubles, and Decimals.
| Category | Math |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $abs: <numeric-expression> }
⚙️ Parameters
| numeric value | A numeric value or an expression resolving to one. |
|---|
Returns:The absolute value; null when the argument is null or missing
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $abs: compute the gap between actual and target
db.sales.aggregate([
{ $project: {
gap: { $abs: { $subtract: ['$actual', '$target'] } }
} }
])
Output:
{ '_id': 1, 'gap': 5 }
{ '_id': 2, 'gap': 3 }
📌 Notes
- Null or missing arguments yield null
- Negative infinity becomes positive infinity
- The sign disappears after abs; pair with $sign when the original sign matters
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhat does $abs return for null?
AIt returns null; wrap with $ifNull when you need a default.
QCan $abs take the absolute value of negative infinity?
AYes, the result is Infinity.
QHow do I get both the sign and the absolute value?
AUse $sign for the sign (1, -1, or 0) and $abs for the magnitude.