

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

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

Amazon DocumentDB 中的`$substrCP`运算符用于从字符串中提取子字符串，其中子字符串指定为 UTF-8 码点范围 (CP)。此运算符在处理 Unicode 字符串时特别有用，因为它允许您提取子字符串，而不必担心字符的底层字节表示形式。

与对字节位置进行`$substrBytes`操作的运算符不同，该`$substrCP`运算符使用码点位置。这使得处理包含非 ASCII 字符的字符串变得更加容易，因为代码点的数量可能与字节数或字符数不匹配。

**参数**
+ `string`：要从中提取子字符串的输入字符串。
+ `start`：从中提取子字符串的起始码点位置（从零开始）。
+ `length`：要提取的代码点数。

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

在此示例中，我们将使用`$substrCP`运算符从包含员工办公桌位置的字符串中提取州缩写。

**创建示例文档**

```
db.people.insert([
  { "_id": 1, "first_name": "Jane", "last_name": "Doe", "Desk": "12 Main St, Minneapolis, MN 55401" },
  { "_id": 2, "first_name": "John", "last_name": "Doe", "Desk": "456 Oak Rd, New Orleans, LA 70032" },
  { "_id": 3, "first_name": "Steve", "last_name": "Smith", "Desk": "789 Elm Ln, Bakersfield, CA 93263" }
]);
```

**查询示例**

```
db.people.aggregate([
  {
    $project: {
      "state": { $substrCP: ["$Desk", 25, 2] }
    }
  }
]);
```

**输出**

```
{ "_id" : 1, "state" : "MN" }
{ "_id" : 2, "state" : "LA" }
{ "_id" : 3, "state" : "CA" }
```

在此示例中，我们知道州缩写从`Desk`字段的第 25 个代码点开始，长度为 2 个代码点。通过使用`$substrCP`运算符，我们可以提取状态缩写，而不必担心字符串的底层字节表示形式。

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

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

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

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

async function findStates() {
  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 result = await db.collection('people').aggregate([
    {
      $project: {
        "state": { $substrCP: ["$Desk", 25, 2] }
      }
    }
  ]).toArray();
  console.log(result);
  client.close();
}

findStates();
```

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

```
from pymongo import MongoClient

def find_states():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    result = list(db.people.aggregate([
        {
            '$project': {
                'state': { '$substrCP': ['$Desk', 25, 2] }
            }
        }
    ]))
    print(result)
    client.close()

find_states()
```

在 Node.js 和 Python 示例中，我们都使用`$substrCP`运算符从`Desk`字段中提取状态缩写，类似于 MongoDB 命令行管理程序示例。

------