$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.
| Category | Math |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $sign: <numeric-expression> }
⚙️ Parameters
| numeric value | A 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
- Zero returns 0, including both signed zeros
- NaN input returns NaN
- Pair with $abs to get direction plus magnitude
🏷️ Related Tags
💡 Related Cases
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.