$atan2 (aggregation)

    在本页面

    $atan2

    4.2版中的新功能。

    返回y / x的反正切(弧形切线),其中yx是分别传递给表达式的第一个和第二个值。

    $atan2具有以下语法:

    1. { $atan2: [ <expression 1>, <expression 2> ] }

    $atan2接受可解析为数字的任何有效表达式。

    $atan2返回以弧度为单位的值。使用 $radiansToDegrees运算符将输出值从弧度转换为度。

    默认情况下以形式$atan2返回值double$atan2也可以返回值作为 128-bit小数,只要该<expression>解析为一个128-bit的十进制值。

    有关表达式的更多信息,请参见 表达式。

    行为

    nullNaN

    如果的第一个参数$atan2null,则 $atan2返回null。如果的第一个参数 $atan2NaN,则$atan2返回NaN。如果第一个参数解析为数字第二个参数解析为NaNnull$atan2则分别返回NaNnull

    例子 结果
    { $atan2: [ NaN, <value> ] }
    or
    { $atan2: [ <value>, NaN ] }
    NaN
    { $atan2: [ null, <value> ] }
    or
    { $atan2: [ <value>, null ] }
    null

    例子

    度数的反正切值

    trigonometry集合包含一个文档,该文档存储直角三角形的三个边:

    1. {
    2. "_id" : ObjectId("5c50782193f833234ba90d85"),
    3. "side_a" : NumberDecimal("3"),
    4. "side_b" : NumberDecimal("4"),
    5. "hypotenuse" : NumberDecimal("5")
    6. }

    以下聚合操作使用该 $atan2表达式来计算side_a$addFields管道之间相邻的角度并将其添加到输入文档中 。

    1. db.trigonometry.aggregate([
    2. {
    3. $addFields : {
    4. "angle_a" : {
    5. $radiansToDegrees : {
    6. $atan2 : [ "$side_b", "$side_a" ]
    7. }
    8. }
    9. }
    10. }
    11. ])

    $radiansToDegrees表达式将返回的弧度值转换为$atan2以度为单位的等效值。

    该命令返回以下输出:

    1. {
    2. "_id" : ObjectId("5c50782193f833234ba90d85"),
    3. "side_a" : NumberDecimal("3"),
    4. "side_b" : NumberDecimal("4"),
    5. "hypotenuse" : NumberDecimal("5"),
    6. "angle_a" : NumberDecimal("53.13010235415597870314438744090658")
    7. }

    由于side_bside_a被存储为 128-bit小数,因此输出 $atan2为128-bit小数。

    弧度的反正切值

    trigonometry集合包含一个文档,该文档存储直角三角形的三个边:

    1. {
    2. "_id" : ObjectId("5c50782193f833234ba90d85"),
    3. "side_a" : NumberDecimal("3"),
    4. "side_b" : NumberDecimal("4"),
    5. "hypotenuse" : NumberDecimal("5")
    6. }

    以下聚合操作使用该 $atan2表达式来计算side_a$addFields管道之间相邻的角度并将其添加到输入文档中 。

    1. db.trigonometry.aggregate([
    2. {
    3. $addFields : {
    4. "angle_a" : {
    5. $atan2 : [ "$side_b", "$side_a" ]
    6. }
    7. }
    8. }
    9. ])

    该命令返回以下输出:

    1. {
    2. "_id" : ObjectId("5c50782193f833234ba90d85"),
    3. "side_a" : NumberDecimal("3"),
    4. "side_b" : NumberDecimal("4"),
    5. "hypotenuse" : NumberDecimal("5"),
    6. "angle_a" : NumberDecimal("0.9272952180016122324285124629224287")
    7. }

    由于side_bside_a被存储为 128-bit小数,因此输出 $atan2为128-bit小数。

    译者:李冠飞

    校对: