

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

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

Amazon DocumentDB 中的`$substrCP`運算子用於從字串擷取子字串，其中子字串指定為 UTF-8 程式碼點 (CP) 的範圍。此運算子在使用 Unicode 字串時特別有用，因為它可讓您擷取子字串，而不必擔心字元的基礎位元組表示法。

與在位元組位置上操作的`$substrBytes`運算子不同，運算`$substrCP`子使用程式碼點位置。這可讓您更輕鬆地使用包含非 ASCII 字元的字串，因為程式碼點的數量可能不符合位元組或字元的數量。

**參數**
+ `string`：要從中擷取子字串的輸入字串。
+ `start`：要從中擷取子字串的起始碼點位置 （以零為基礎）。
+ `length`：要擷取的程式碼點數目。

## 範例 (MongoDB Shell)
<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 Shell 範例。

------