

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

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

4.0 版的新增内容

Amazon DocumentDB 中的`$trim`运算符用于从字符串中删除前导 and/or 尾随的空格字符。

**参数**
+ `input`: 要修剪的字符串表达式。
+ `chars`:（可选）指定要从输入的开头和结尾修剪的字符，默认为空格。

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

以下示例演示如何使用`$trim`运算符从字符串中删除前导和尾随空格。

**创建示例文档**

```
db.people.insertMany([
  { "name": "   John Doe   " },
  { "name": "   Bob Johnson   " }
])
```

**查询示例**

```
db.people.aggregate([
  { $project: {
    "name": { $trim: {input: "$name"}}
  }}
])
```

**输出**

```
[
  { "name": "John Doe" },
  { "name": "Bob Johnson" }
]
```

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

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

------
#### [ 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 collection = db.collection('people');

  const result = await collection.aggregate([
    { $project: {
      "name": { $trim: {input: "$name" }}
    }}
  ]).toArray();

  console.log(result);
  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']
    collection = db['people']

    result = list(collection.aggregate([
        {"$project": {
            "name": {"$trim": {"input": "$name"}}
        }}
    ]))

    print(result)
    client.close()

example()
```

------