MongoDB $tanh Operator

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

What You’ll Learn

The $tanh operator computes the hyperbolic tangent of a number in MongoDB aggregation pipelines. Output is always between -1 and 1, making it useful for normalization, sigmoid-style transforms, and ML-related scoring.

01

Hyperbolic Tan

tanh(x).

02

Syntax

One expression.

03

Bounded

-1 to 1 output.

04

$project Stage

Transform fields.

05

Use Cases

ML, normalization.

06

vs $tan

Hyperbolic vs trig.

Definition and Usage

In MongoDB’s aggregation framework, the $tanh operator returns the hyperbolic tangent of a numeric expression. Mathematically, tanh(x) = sinh(x) / cosh(x). For example, { $tanh: 0 } returns 0, and { $tanh: 1 } returns approximately 0.761594.

Unlike trigonometric $tan, hyperbolic tangent takes any real number (not an angle in radians) and always produces a value strictly between -1 and 1. Large positive inputs approach 1; large negative inputs approach -1.

💡
Beginner Tip

Think of $tanh as MongoDB’s version of JavaScript’s Math.tanh(). It is an odd function: tanh(-x) = -tanh(x).

📝 Syntax

The $tanh operator takes one numeric expression:

mongosh
{ $tanh: <expression> }

Literal Examples

mongosh
{ $tanh: 0 }
// Result: 0

{ $tanh: 1 }
// Result: ~0.761594

{ $tanh: -1 }
// Result: ~-0.761594

{ $tanh: "$value" }
// Hyperbolic tangent of the value field

Syntax Rules

  • $tanh — returns the hyperbolic tangent of the expression.
  • <expression> — any real number (field path, literal, or nested expression).
  • Output range — always between -1 and 1 (exclusive at extremes).
  • tanh(0) — always 0.
  • Use inside $project, $addFields, or $set.
  • null input — returns null.

💡 $tanh vs $tan vs $sinh

$tanh — hyperbolic tangent; input = any real number; output in (-1, 1)
$tan — trigonometric tangent; input = angle in radians; unbounded
$sinh — hyperbolic sine; related function; output unbounded
tanh(x) = sinh(x) / cosh(x) — use $tanh when you need the bounded ratio.

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (hyperbolic)
Syntax{ $tanh: <expression> }
InputAny real number
Output rangeBetween -1 and 1
tanh(0)0
Common stages$project, $addFields, $set
Field
{
  $tanh: "$value"
}

On a field

Zero
{
  $tanh: 0
}

Returns 0

Large x
{
  $tanh: 10
}

Approaches 1

Odd fn
tanh(-x)
= -tanh(x)

Sign flip

Examples Gallery

Compute hyperbolic tangents on document fields, verify odd-function behavior, and apply sigmoid-style normalization.

📚 Basic Hyperbolic Tangent

Start with a data collection and apply $tanh with $project.

Sample Input Documents

Suppose you have a data collection with numeric value fields:

mongosh
[
  { "_id": 1, "value": 1 },
  { "_id": 2, "value": 0.5 },
  { "_id": 3, "value": -1 },
  { "_id": 4, "value": 0 }
]

Example 1 — Basic $tanh on a Field

Compute the hyperbolic tangent of each value:

mongosh
db.data.aggregate([
  {
    $project: {
      value: 1,
      tanhValue: { $tanh: "$value" }
    }
  }
])

How It Works

  • Document 1: tanh(1) ≈ 0.761594.
  • Document 2: tanh(0.5) ≈ 0.462117.
  • Document 3: tanh(-1) ≈ -0.761594 (odd function).
  • Document 4: tanh(0) = 0.

📈 Scaling and Comparison

See how large values saturate and compare with related operators.

Example 2 — Odd Function Behavior

Verify that tanh(-x) equals -tanh(x):

mongosh
db.data.aggregate([
  {
    $project: {
      positive: { $tanh: 2 },
      negative: { $tanh: -2 }
    }
  }
])

// positive: ~0.964028
// negative: ~-0.964028

How It Works

Hyperbolic tangent is an odd function. Negative inputs produce the negated result of the positive counterpart.

Example 3 — Saturation for Large Values

Large inputs approach but never exceed 1 or -1:

mongosh
db.data.aggregate([
  {
    $project: {
      small:  { $tanh: 0.5 },
      medium: { $tanh: 2 },
      large:  { $tanh: 10 }
    }
  }
])

// $tanh(0.5)  → ~0.462
// $tanh(2)    → ~0.964
// $tanh(10)   → ~0.9999999959 (approaches 1)

How It Works

This saturation property makes $tanh useful for squashing unbounded scores into a fixed range.

Example 4 — Sigmoid-Style Score Normalization

Transform raw model scores into a bounded activation range:

mongosh
db.predictions.aggregate([
  {
    $project: {
      modelId: 1,
      rawScore: 1,
      activation: { $tanh: "$rawScore" }
    }
  }
])

// rawScore: 3.5  → activation: ~0.998
// rawScore: 0    → activation: 0
// rawScore: -2.1 → activation: ~-0.97

How It Works

In machine learning pipelines, tanh acts like a sigmoid activation, mapping any real score into (-1, 1) for downstream processing.

Bonus — tanh as sinh / cosh

Mathematically, tanh equals sinh divided by cosh:

mongosh
db.data.aggregate([
  {
    $project: {
      value: 1,
      viaTanh: { $tanh: "$value" },
      viaRatio: {
        $divide: [
          { $sinh: "$value" },
          { $cosh: "$value" }
        ]
      }
    }
  }
])

How It Works

Both expressions produce the same result. Use $tanh directly for clarity and performance.

🚀 Use Cases

  • Machine learning scoring — apply tanh activation to normalize model outputs in aggregation pipelines.
  • Data normalization — squash unbounded metrics into the range (-1, 1).
  • Signal processing — nonlinear transforms for filtering and feature extraction.
  • Mathematical modeling — compute hyperbolic relationships stored alongside raw measurements.

🧠 How $tanh Works

1

MongoDB reads the expression

The input resolves to a real number from a field path, literal, or nested expression.

Input
2

Hyperbolic tangent is computed

MongoDB evaluates tanh(x) = (ex - e-x) / (ex + e-x).

Compute
3

A bounded result is returned

The output is always between -1 and 1, stored in your pipeline field.

Output
=

Normalized value

Use for activations, bounded scores, or further math in the pipeline.

Conclusion

The $tanh operator computes hyperbolic tangent in MongoDB aggregation pipelines, producing values strictly between -1 and 1. It is essential for sigmoid-style normalization, ML scoring, and any task that needs to bound unbounded numeric data.

Do not confuse it with trigonometric $tan, which expects radians and is unbounded. Next in the series: $text.

💡 Best Practices

✅ Do

  • Use $tanh to squash unbounded scores into (-1, 1)
  • Remember tanh(0) = 0 for zero-centered data
  • Pair with $sinh and $cosh when building custom math
  • Guard null fields with $ifNull before applying $tanh
  • Test with positive, negative, and zero inputs

❌ Don’t

  • Confuse $tanh (hyperbolic) with $tan (trigonometric)
  • Pass angles in radians to $tanh expecting trig behavior
  • Expect output outside the range -1 to 1
  • Assume $tanh works as a query filter outside expressions
  • Forget that null input returns null

Key Takeaways

Knowledge Unlocked

Five things to remember about $tanh

Use these points when applying hyperbolic tangent in MongoDB.

5
Core concepts
📝 02

{ $tanh: x }

One argument.

Syntax
🔢 03

-1 to 1

Bounded.

Output
🛠 04

Sigmoid-like

ML activation.

Use case
05

vs $tan

Not trig.

Compare

❓ Frequently Asked Questions

$tanh returns the hyperbolic tangent of a numeric value. The result is always between -1 and 1. It is an aggregation expression operator used inside stages like $project and $addFields.
The syntax is { $tanh: <expression> }. The expression can be a field reference like "$value", a literal number, or another numeric expression.
$tan is trigonometric tangent of an angle in radians (periodic, unbounded). $tanh is hyperbolic tangent of a real number (bounded between -1 and 1, sigmoid-shaped). They are different functions.
Hyperbolic tangent squashes values into the range (-1, 1), similar to a sigmoid activation. It is useful for normalizing scores and modeling nonlinear relationships in aggregation pipelines.
$tanh returns null when the input is null. It does not throw an error. Use $ifNull when the field may be missing.

Continue the Operator Series

Move on to $text for full-text search queries, or review $sinh for hyperbolic sine.

Next: $text →

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