

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

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

4.0 版的新增内容

Amazon DocumentDB 中的`$convert`运算符用于将值从一种数据类型转换为另一种数据类型。当您需要对不同类型的数据执行操作时，此运算符很有用，例如将字符串转换为数字或将日期转换为时间戳。

**参数**
+ `to`：要将值转换为的目标数据类型。支持的值有 `"string"`、`"double"`、`"long"`、`"int"`、`"date"` 和 `"boolean"`。
+ `from`：该值的当前数据类型。如果未指定，Amazon DocumentDB 将尝试自动检测数据类型。
+ `onError`:（可选）转换失败时要返回的值。可以是特定值或以下特殊值之一：`"null"``"zerofill"`、或`"error"`。
+ `onNull`:（可选）如果输入值为，则返回的值`null`。可以是特定值或以下特殊值之一：`"null"``"zerofill"`、或`"error"`。

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

以下示例演示如何使用`$convert`运算符将字符串值转换为日期。

**创建示例文档**

```
db.users.insertMany([
  { _id: 1, name: "John Doe", joinedOn: "2022-01-01" },
  { _id: 2, name: "Jane Smith", joinedOn: "2023-02-15" },
  { _id: 3, name: "Bob Johnson", joinedOn: "invalid date" }
]);
```

**查询示例**

```
db.users.aggregate([
  {
    $project: {
      _id: 1,
      name: 1,
      joinedOn: {
        $convert: {
          input: "$joinedOn",
          to: "date",
          onError: "null",
          onNull: "null"
        }
      }
    }
  }
])
```

**输出**

```
[
  { "_id" : 1, "name" : "John Doe", "joinedOn" : ISODate("2022-01-01T00:00:00Z") },
  { "_id" : 2, "name" : "Jane Smith", "joinedOn" : ISODate("2023-02-15T00:00:00Z") },
  { "_id" : 3, "name" : "Bob Johnson", "joinedOn" : null }
]
```

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

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

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

```
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 users = db.collection("users");

  const results = await users.aggregate([
    {
      $project: {
        _id: 1,
        name: 1,
        joinedOn: {
          $convert: {
            input: "$joinedOn",
            to: "date",
            onError: "null",
            onNull: "null"
          }
        }
      }
    }
  ]).toArray();

  console.log(results);
  client.close();
}

example();
```

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

```
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"]
    users = db["users"]

    results = list(users.aggregate([
        {
            "$project": {
                "_id": 1,
                "name": 1,
                "joinedOn": {
                    "$convert": {
                        "input": "$joinedOn",
                        "to": "date",
                        "onError": "null",
                        "onNull": "null"
                    }
                }
            }
        }
    ]))

    print(results)
    client.close()

example()
```

------