$sign (Sign)

Last updated: 2026-10-09

$sign (Sign)

$sign returns the sign of a number: 1 for positives, -1 for negatives, and 0 for zero. It is used for category counts, up/down direction checks, and data bucketing, such as mapping a price change to up, down, or flat. A null or missing argument yields null, and NaN input returns NaN. Combined with $abs it yields both direction and magnitude of a value, which is more concise than chained comparisons in a conditional expression and handy for later group-by counting.

CategoryMath
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $sign: <numeric-expression> }

⚙️ Parameters

numeric valueA numeric value or an expression resolving to one.

Returns:1, -1, or 0; NaN for NaN input, null when null or missing

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// $sign: direction of a price change
db.stocks.aggregate([
  { $project: {
      trend: { $sign: '$change' }
  } }
])

Output:

{ '_id': 1, 'trend': 1 }
{ '_id': 2, 'trend': -1 }

📌 Notes

More hands-on cases coming soon.

📚 Related Tutorials

❓ FAQ

QWhat values does $sign return?
AThree values: 1 for positives, -1 for negatives, and 0 for zero.
QWhat does $sign return for zero?
AIt returns 0; both signed zeros count as zero.
QCan $sign detect rises and falls?
AYes, pass a price difference to $sign: 1 means up, -1 means down, and 0 means flat.
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%

🙏 帮我们做得更好

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

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