In MongoDB, the $atan
aggregation pipeline operator returns the arctangent (inverse tangent) of a value.
The return value is in radians.
$atan
accepts any valid expression that resolves to a number.
The $atan
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 $atan
operator to return the arctangent of the data
field:
db.test.aggregate(
[
{ $match: { _id: 1 } },
{ $project: {
_id: 0,
arctangent: { $atan: "$data" }
}
}
]
)
Result:
{ "arctangent" : 1.1071487177940906 }
Convert to Degrees
As mentioned, $atan
returns its result in radians. You can use the $radiansToDegrees
operator if you want the result in degrees.
Example:
db.test.aggregate(
[
{ $match: { _id: 1 } },
{ $project: {
_id: 0,
radians: { $atan: "$data" },
degrees: { $radiansToDegrees: { $atan: "$data" } }
}
}
]
)
Result:
{ "radians" : 1.1071487177940906, "degrees" : 63.43494882292202 }
In this example, the first field presents the result in radians, and the second field presents it in degrees.
128-Bit Decimal Values
By default, the $atan
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 run the the $atan
operator against that document:
db.test.aggregate(
[
{ $match: { _id: 2 } },
{ $project: {
_id: 0,
arctangent: { $atan: "$data" }
}
}
]
)
Result:
{ "arctangent" : NumberDecimal("1.131877001503761613330938729211760") }
The output is 128-bit decimal.
Null Values
Null values return null
when using the $atan
operator.
Suppose we add the following document to our collection:
{ "_id" : 3, "data" : null }
Let’s run the the $atan
operator against that document:
db.test.aggregate(
[
{ $match: { _id: 3 } },
{ $project: {
_id: 0,
result: { $atan: "$data" }
}
}
]
)
Result:
{ "result" : null }
We can see that the result is null
.
NaN Values
If the argument resolves to NaN
, $atan
returns NaN
.
Example:
db.test.aggregate(
[
{ $match: { _id: 3 } },
{ $project: {
_id: 0,
result: { $atan: 1 * "$data" }
}
}
]
)
Result:
{ "result" : NaN }
Non-Existent Fields
If the $atan
operator is applied against a field that doesn’t exist, null
is returned.
Example:
db.test.aggregate(
[
{ $match: { _id: 3 } },
{ $project: {
_id: 0,
result: { $atan: "$wrong" }
}
}
]
)
Result:
{ "result" : null }