

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

# \$1pow
<a name="pow"></a>

在 8.0 中引入

Amazon DocumentDB 中的`$pow`运算符允许您将数字提高为次方。这对于在聚合管道中执行指数计算非常有用。

**参数**
+ `<number>`（必填）：要提高为次的数字。
+ `<exponent>`（必填）：应将数字提高到的次方。

## 示例（MongoDB 外壳）
<a name="pow-examples"></a>

以下示例演示如何使用`$pow`运算符计算数字的平方。

**创建示例文档**

```
db.numbers.insertMany([
  { "_id": 1, "value": 2 },
  { "_id": 2, "value": 3 },
  { "_id": 3, "value": 4 }
]);
```

**查询示例**

```
db.numbers.aggregate([
  { $addFields: { "square": { $pow: ["$value", 2] } } }
])
```

**输出**

```
[
  { "_id": 1, "value": 2, "square": 4 },
  { "_id": 2, "value": 3, "square": 9 },
  { "_id": 3, "value": 4, "square": 16 }
]
```

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

要查看使用该`$pow`命令的代码示例，请选择要使用的语言的选项卡：

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

以下是在 Node.js 应用程序中使用 \$1pow 运算符的示例：

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

async function example() {
  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('numbers');

  const result = await collection.aggregate([
    { $addFields: { "square": { $pow: ["$value", 2] } } }
  ]).toArray();

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

example();
```

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

以下是在 Python 应用程序中使用 \$1pow 运算符的示例：

```
from pymongo import MongoClient

def example():
    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['numbers']

    result = list(collection.aggregate([
        { "$addFields": { "square": { "$pow": ["$value", 2] } } }
    ]))

    print(result)
    client.close()

example()
```

------