In MongoDB, the $tanh
aggregation pipeline operator returns the hyperbolic tangent of a value that is measured in radians.
$tanh
accepts any valid expression that resolves to a number.
The $tanh
operator was introduced in MongoDB 4.2.
Example
Suppose we have a collection called test
with the following document:
{ "_id" : 1, "data" : 2 }
We can use the $tanh
operator to return the hyperbolic tangent of the data
field:
db.test.aggregate(
[
{ $match: { _id: 1 } },
{ $project: {
_id: 0,
hyperbolicTangent: { $tanh: "$data" }
}
}
]
)
Result:
{ "hyperbolicTangent" : 0.9640275800758169 }
Convert to Radians
As mentioned, $tanh
returns the hyperbolic tangent of a value that is measured in radians. If the value is in degrees, you can use the $degreesToRadians
operator to convert it to radians.
Example:
db.test.aggregate(
[
{ $match: { _id: 1 } },
{ $project: {
_id: 0,
hyperbolicTangent: { $degreesToRadians: { $tanh: "$data" } }
}
}
]
)
Result:
{ "hyperbolicTangent" : 0.016825455352356293 }
128-Bit Decimal Values
By default, the $tanh
operator returns values as a double
, but it can also return values as a 128-bit decimal as long as the expression resolves to a 128-bit decimal value.
Suppose we add the following document to our collection:
{ "_id" : 2, "data" : NumberDecimal("2.1301023541559787031443874490659") }
Let’s apply the the $tanh
operator against the data
field in that document:
db.test.aggregate(
[
{ $match: { _id: 2 } },
{ $project: {
_id: 0,
result: { $tanh: "$data" }
}
}
]
)
Result:
{ "result" : NumberDecimal("0.9721543408207801550541565157881927") }
The output is 128-bit decimal.
Null Values
Null values return null
when using the $tanh
operator.
Suppose we add the following document to our collection:
{ "_id" : 3, "data" : null }
Let’s apply the the $tanh
operator against that document:
db.test.aggregate(
[
{ $match: { _id: 3 } },
{ $project: {
_id: 0,
result: { $tanh: "$data" }
}
}
]
)
Result:
{ "result" : null }
We can see that the result is null
.
NaN Values
If the argument resolves to NaN
, $tanh
returns NaN
.
Example:
db.test.aggregate(
[
{ $match: { _id: 1 } },
{ $project: {
_id: 0,
result: { $tanh: 1 * "$data" }
}
}
]
)
Result:
{ "result" : NaN }
Non-Existent Fields
If the $tanh
operator is applied against a field that doesn’t exist, null
is returned.
Example:
db.test.aggregate(
[
{ $match: { _id: 1 } },
{ $project: {
_id: 0,
result: { $tanh: "$name" }
}
}
]
)
Result:
{ "result" : null }
Infinity
Providing Infinity
returns 1
and providing -Infinity
returns -1
.
Suppose we add the following documents to the collection:
{ "_id" : 4, "data" : Infinity } { "_id" : 5, "data" : -Infinity }
Let’s apply $tanh
to these documents:
db.test.aggregate(
[
{ $match: { _id: { $in: [ 4, 5 ] } } },
{ $project: {
hyperbolicTangent: { $tanh: "$data" }
}
}
]
)
Result:
{ "_id" : 4, "hyperbolicTangent" : 1 } { "_id" : 5, "hyperbolicTangent" : -1 }