$atan2返回
y / x的反正切,其中y和x分别是传递给表达式的第一个值和第二个值。$atan2通过以下语法实现:{ $atan2: [ <expression 1>, <expression 2> ] } $atan2takes any valid expression that resolves to a number.$atan2returns values in radians. Use$radiansToDegreesoperator to convert the output value from radians to degrees.By default
$atan2returns values as adouble.$atan2can also return values as a 128-bit decimal as long as the<expression>resolves to a 128-bit decimal value.有关表达式的更多信息,请参阅表达式。
行为
null 和 NaN
如果赋予$atan2的任一参数为null ,则表达式返回null 。 如果任一参数为NaN ,则表达式返回NaN 。 如果一个参数为null ,另一个为NaN ,则表达式返回null 。
例子 | 结果 |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
例子
trigonometry 集合包含一个文档,该文档存储直角三角形的三条边:
{ "_id" : ObjectId("5c50782193f833234ba90d85"), "side_a" : Decimal128("3"), "side_b" : Decimal128("4"), "hypotenuse" : Decimal128("5") }
The following aggregation operation uses the $atan2 expression to calculate the angle adjacent to side_a and add it to the input document using the $addFields pipeline stage.
db.trigonometry.aggregate([ { $addFields : { "angle_a" : { $radiansToDegrees : { $atan2 : [ "$side_b", "$side_a" ] } } } } ])
The $radiansToDegrees expression converts the radian value returned by $atan2 to the equivalent value in degrees.
该命令返回以下输出:
{ "_id" : ObjectId("5c50782193f833234ba90d85"), "side_a" : Decimal128("3"), "side_b" : Decimal128("4"), "hypotenuse" : Decimal128("5"), "angle_a" : Decimal128("53.13010235415597870314438744090658") }
Since side_b and side_a are stored as 128-bit decimals, the output of $atan2 is a 128-bit decimal.
trigonometry 集合包含一个文档,该文档存储直角三角形的三条边:
{ "_id" : ObjectId("5c50782193f833234ba90d85"), "side_a" : Decimal128("3"), "side_b" : Decimal128("4"), "hypotenuse" : Decimal128("5") }
The following aggregation operation uses the $atan2 expression to calculate the angle adjacent to side_a and add it to the input document using the $addFields pipeline stage.
db.trigonometry.aggregate([ { $addFields : { "angle_a" : { $atan2 : [ "$side_b", "$side_a" ] } } } ])
该命令返回以下输出:
{ "_id" : ObjectId("5c50782193f833234ba90d85"), "side_a" : Decimal128("3"), "side_b" : Decimal128("4"), "hypotenuse" : Decimal128("5"), "angle_a" : Decimal128("0.9272952180016122324285124629224287") }
Since side_b and side_a are stored as 128-bit decimals, the output of $atan2 is a 128-bit decimal.