$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.

CategoryMath
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $abs: <numeric-expression> }

⚙️ Parameters

numeric valueA 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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏