

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

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

8.0.1 版的新功能。

Amazon DocumentDB 中的`$atan2`運算子會傳回 的反正切 (arc 正切）`y / x`，其中 `y`和 分別`x`是傳遞給表達式的第一和第二個值。

兩個表達式都必須解析為數值。運算子使用兩個引數的符號來判斷正確的 1/4。

結果以弧度表示。若要取得度數，請`$radiansToDegrees`套用至輸出。

傳回類型預設為 `double` 。如果輸入是 128 位元的小數位數，則輸出也是 128 位元的小數位數。

**參數**
+ `expression 1` (y)：解析為代表 y 座標之數字的表達式。
+ `expression 2` (x)：解析為代表 x 座標之數字的表達式。

## Behavior (行為)
<a name="atan2-behavior"></a>

**Null 和 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()
```

------