

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# $atan2
<a name="atan2"></a>

8.0.1 版中的新内容。

Amazon DocumentDB 中的`$atan2`运算符返回的反正切值（反正切）`y / x`，其中`y`和`x`分别是传递给表达式的第一个和第二个值。

这两个表达式都必须解析为数值。运算符使用两个参数的符号来确定正确的象限。

结果以弧度为单位。要获得度数，请应用`$radiansToDegrees`于输出。

`double`默认情况下，返回类型为。如果输入是 128 位小数，则输出也是 128 位十进制。

**参数**
+ `expression 1`(y)：解析为表示 y 坐标的数字的表达式。
+ `expression 2`(x)：解析为表示 x 坐标的数字的表达式。

## 行为
<a name="atan2-behavior"></a>

**空值和 NaN **

如果任一参数是`null`（或引用缺失字段），则结果为`null`。如果任一参数是`NaN`，则结果为`NaN`。当一个参数为`null`而另一个参数为时`NaN`，优`null`先。


| 示例 | 结果 | 
| --- | --- | 
| { $atan2: [ NaN, <value> ] } | NaN | 
| { $atan2: [ <value>, NaN ] } | NaN | 
| { $atan2: [ null, <value> ] } | null | 
| { $atan2: [ <value>, null ] } | null | 
| { $atan2: [ NaN, null ] } | null | 
| { $atan2: [ null, NaN ] } | null | 

## 示例（MongoDB Shell）
<a name="atan2-examples"></a>

以下示例说明如何使用`$atan2`运算符计算一组点 y/x 的反正切值。

**创建示例文档 **

```
db.points.insertMany([
  { "_id": 1, "y": 1, "x": 1 },
  { "_id": 2, "y": 1, "x": 0 },
  { "_id": 3, "y": -1, "x": -1 }
]);
```

**查询示例 **

```
db.points.aggregate([
  { $project: {
    "angle": { $atan2: ["$y", "$x"] }
  }}
]);
```

**输出**

```
[
  { "_id": 1, "angle": 0.7853981633974483 },
  { "_id": 2, "angle": 1.5707963267948966 },
  { "_id": 3, "angle": -2.356194490192345 }
]
```

## 代码示例
<a name="atan2-code"></a>

要查看使用`$atan2`运算符的代码示例，请选择要使用的语言的选项卡：

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('points');

  const result = await collection.aggregate([
    { $project: {
      "angle": { $atan2: ["$y", "$x"] }
    }}
  ]).toArray();

  console.log(result);
  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def main():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['points']

    result = list(collection.aggregate([
        { '$project': {
            'angle': { '$atan2': ['$y', '$x'] }
        }}
    ]))

    print(result)
    client.close()

if __name__ == "__main__":
    main()
```

------