MongoDB $tanh Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $tanh?

$tanh is a MongoDB aggregation expression that returns the hyperbolic tangent of a number. The result always sits in (-1, 1)—useful for gently squashing scores. It is not the same as trigonometric $tan.

Remember
$tanh = Math.tanh for aggregation

{ $tanh: <expression> }

input  → number (radians if you treat it as an angle)
output → value in (-1, 1)

null / missing → null
NaN → NaN
+Infinity → 1
-Infinity → -1
UsePrefer
Hyperbolic tangent / score squash$tanh
Trigonometric tangent of an angle$tan
Inverse hyperbolic tangent$atanh

How to Use $tanh in MongoDB

Pass a number (or convert degrees first), then read the squashed result in (-1, 1).

  1. Choose an expression stage ($addFields or $project).
  2. If the field stores degrees, convert with $degreesToRadians.
  3. Pass that expression to $tanh.
  4. Use the result as a normalized score or feature value.
PieceRequired?Role
$tanhYesHyperbolic tangent → (-1, 1)
ExpressionYesNumber, field, or nested math
$degreesToRadiansNoOnly when the stored value is in degrees

Pseudocode

Pseudocode
for each document:
    x = evaluate(expression)
    if x is null or missing:
        result = null
    else if x is NaN:
        result = NaN
    else if x is +Infinity:
        result = 1
    else if x is -Infinity:
        result = -1
    else:
        result = tanh(x)   // in (-1, 1)
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while writing hyperbolic-tangent expressions.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $tanh: <expression> }
Output range(-1, 1) for finite inputs
Sample checktanh(0) = 0, tanh(1) ≈ 0.7616
Degrees pattern{ $tanh: { $degreesToRadians: <deg> } }
vs $tanHyperbolic vs trigonometric—different math
Infinity+∞ → 1, -∞ → -1

Live Preview

Watch $tanh squash a number into (-1, 1). Larger magnitudes move closer to the edges.

Simulates $tanh (same idea as the mongosh examples below).

Result
x = 1
$tanh → 0.761594

{ tanh: 0.761594 }

Worked Walkthrough — Squash a Score

Start with score x = 1. Hyperbolic tangent maps it into (-1, 1) without hard clipping.

Calculation
Document:
  { x: 1 }

tanh(1) ≈ 0.7616

Compare:
  tanh(0) = 0
  tanh(2) ≈ 0.9640   // closer to 1
  tanh(-1) ≈ -0.7616 // odd / symmetric

Check: output stays inside (-1, 1) ✓

MongoDB Examples

We store one score, then apply $tanh. Example 3 shows the same idea with a degree-style value (like the MongoDB docs). Insert the sample data once in mongosh.

Example 1 — Sample Data

Imagine one numeric score 1 and one angle in degrees 0. We save both in a collection named hyperbolic.

mongosh
db.hyperbolic.insertOne({
  _id: 1,
  x: 1,
  angle_deg: 0
});

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps one document in hyperbolic. Run find() to see it:

mongosh
db.hyperbolic.find()

Read that document like this:

Field in MongoDBValuePlain English
_id1Document id (row number for this lesson)
x1Plain numeric score to squash
angle_deg0Angle in degrees (for Example 3)
Picture
Hyperbolic tangent (S-shaped squash):

  input x     tanh(x)
  --------    --------
     -2   →   ≈ -0.96
     -1   →   ≈ -0.76
      0   →      0
      1   →   ≈  0.76
      2   →   ≈  0.96

  Always stays inside (-1, 1)

How It Works

  1. Insert once. insertOne adds a single document to hyperbolic.
  2. MongoDB stores fields as written. x is 1; angle_deg is 0.
  3. find() shows the same shape. What you inserted is what you get back—ready for $tanh.

Example 2 — Hyperbolic Tangent

Goal: apply $tanh to the score x (should be about 0.7616).

mongosh
db.hyperbolic.aggregate([
  {
    $addFields: {
      tanh: { $tanh: "$x" }
    }
  }
]);

How It Works

  1. Read the stored score. MongoDB already has x: 1 from Example 1.
  2. Apply hyperbolic tangent. $tanh maps 1 to about 0.7616.
  3. Stay in range. The result is inside (-1, 1)—not a hard clip, a smooth squash.
  4. Keep all fields. $addFields adds tanh next to the original fields.

Example 3 — Degrees Path

Same document: convert angle_deg to radians, then take $tanh. For 0°, the result is 0.

mongosh
db.hyperbolic.aggregate([
  {
    $addFields: {
      tanh_from_deg: {
        $tanh: {
          $degreesToRadians: "$angle_deg"
        }
      }
    }
  }
]);

How It Works

  1. Start from degrees. The document stores angle_deg: 0.
  2. Convert units. $degreesToRadians turns 0° into 0 radians.
  3. Take hyperbolic tangent. tanh(0) = 0.
  4. Same pattern as official docs. Use this wrap whenever a degree field feeds $tanh.

Edge Cases & Pitfalls

Check these before using $tanh in production pipelines.

vs tan

Not the same as $tan

$tan is trigonometric and unbounded. $tanh is hyperbolic and stays in (-1, 1).

infinity

Infinity becomes ±1

+Infinity → 1 and -Infinity → -1. Unlike $tan, this does not throw.

null

Null and missing become null

Missing fields return null. Use $ifNull when you need a default.

inverse

Need the inverse? Use $atanh

$tanh goes number → (-1, 1). To reverse that, use $atanh (input must be in (-1, 1)).

Performance Notes

ApproachCostBest for
$tanh alonePer-document mathScores already numeric
$degreesToRadians + $tanhStill O(docs)Degree-stored angle fields
Filter then $tanhFewer docs processedLarge collections

Hyperbolic math is cheap compared with large sorts or joins. Filter early with $match when only some documents need a squash.

Key Takeaways

  • Role: hyperbolic tangent → value in (-1, 1).
  • Not $tan: different function, different use cases.
  • Infinity: +∞ → 1, -∞ → -1.
  • Degrees: wrap with $degreesToRadians when needed.

One line: $tanh answers “squash this number into (-1, 1)”—smoothly, not with a hard clip.

Frequently Asked Questions

$tanh returns the hyperbolic tangent of a number. The result is always between -1 and 1. Use it inside aggregation expression stages such as $project and $addFields.
$tan is trigonometric tangent of an angle in radians (unbounded, periodic). $tanh is hyperbolic tangent of a real number (bounded in (-1, 1), S-shaped). They are different functions.
MongoDB documents $tanh as taking a numeric value measured in radians. If your field stores degrees, convert with $degreesToRadians first. For score-style numbers, pass the value directly.
Null or a missing field returns null. NaN returns NaN. Positive Infinity returns 1; negative Infinity returns -1.
Hyperbolic tangent gently squashes large positives toward 1 and large negatives toward -1, which is useful for normalizing scores in a pipeline.
Yes for the math. Think of $tanh as MongoDB’s aggregation version of Math.tanh—run it in the pipeline, not as a standalone find() filter.

Next: $text

Search string content with MongoDB text indexes.

$text tutorial →

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.

9 people found this page helpful