

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

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

Amazon DocumentDB 中的`$substrBytes`運算子用於根據指定的位元組範圍從字串中擷取子字串。當您需要從字串中擷取子字串，且代表字串中每個字元所需的位元組數很重要時，此運算子非常有用。

與在 Unicode 程式碼點數量上運作`$substrCP`的 不同， 以代表字串中字元所需的位元組數量`$substrBytes`運作。這在使用包含非 ASCII 字元的字串時特別有用，因為這些字元可能需要多個位元組才能表示。

\$1注意：\$1 自 3.4 版以來`$substr`已棄用。 現在`$substr`是 的別名。 `$substrBytes`

**參數**
+ `string`：將從中擷取子字串的輸入字串。
+ `startByte`：要擷取之子字串的以零為基礎的起始位元組位置。負值可用來從字串結尾指定位置。
+ `length`：子字串中要擷取的位元組數。

## 範例 (MongoDB Shell)
<a name="substrBytes-examples"></a>

在此範例中，我們將使用 從包含非 ASCII 字元的字串中`$substrBytes`擷取子字串。

**建立範例文件**

```
db.people.insertMany([
  { "_id": 1, "Desk": "Düsseldorf-NRW-021" },
  { "_id": 2, "Desk": "Bremerhaven-HBB-32a" },
  { "_id": 3, "Desk": "Norderstedt-SHH-892.50" },
  { "_id": 4, "Desk": "Brandenburg-BBB-78" }
]);
```

**查詢範例**

```
db.people.aggregate([
  {
    $project: {
      "state": { $substrBytes: [ "$Desk", 12, 3] }
    }
  }
])
```

**輸出**

```
{ "_id": 1, "state": "NRW" },
{ "_id": 2, "state": "HBB" },
{ "_id": 3, "state": "SHH" },
{ "_id": 4, "state": "BBB" }
```

在此範例中，我們使用 從 `Desk` 欄位的第 12 個位元組開始`$substrBytes`擷取 3 個位元組的子字串。這可讓我們擷取 2 個字元的狀態縮寫，即使字串可能包含非 ASCII 字元。

## 程式碼範例
<a name="substrBytes-code"></a>

若要檢視使用 `$substrBytes`命令的程式碼範例，請選擇您要使用的語言標籤：

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

  const result = await people.aggregate([
    {
      $project: {
        "state": { $substrBytes: ["$Desk", 12, 3] }
      }
    }
  ]).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
    people = db.people

    result = list(people.aggregate([
        {
            '$project': {
                "state": { '$substrBytes': ["$Desk", 12, 3] }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------