

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

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

Amazon DocumentDB 中的`$strLenCP`運算子用於判斷程式碼點 (Unicode 字元） 中字串表達式的長度。當您需要知道字串中的字元數，而不是位元組數時，這會很有用。

**參數**
+ `expression`：傳回程式碼點長度的字串表達式。

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

下列範例示範 `$strLenCP`運算子的使用情況，以判斷具有 Unicode 字元的字串長度。

**建立範例文件**

```
db.people.insertMany([
  { "_id": 1, "Desk": "Düsseldorf-BVV-021" },
  { "_id": 2, "Desk": "Munich-HGG-32a" },
  { "_id": 3, "Desk": "Cologne-ayu-892.50" },
  { "_id": 4, "Desk": "Dortmund-Hop-78" }
])
```

**查詢範例**

```
db.people.aggregate([
  {
    $project: {
      "Desk": 1,
      "length": { $strLenCP: "$Desk" }
    }
  }
])
```

**輸出**

```
{ "_id" : 1, "Desk" : "Düsseldorf-BVV-021", "length" : 18 }
{ "_id" : 2, "Desk" : "Munich-HGG-32a", "length" : 14 }
{ "_id" : 3, "Desk" : "Cologne-ayu-892.50", "length" : 18 }
{ "_id" : 4, "Desk" : "Dortmund-Hop-78", "length" : 15 }
```

請注意 "Düsseldorf-BVV-021" 字串的長度測量差異，其中包含 Unicode 字元 (Ü)。`$strLenCP` 運算子會正確計算 Unicode 字元的數量，而`$strLenBytes`運算子則會計算位元組的數量。

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

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

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

以下是在 Node.js 應用程式中搭配 MongoDB 驅動程式使用 `$strLenCP` 運算子的範例：

```
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: {
        "Desk": 1,
        "length": { $strLenCP: "$Desk" }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

example();
```

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

以下是在 Python 應用程式中搭配 PyMongo 驅動程式使用 `$strLenCP` 運算子的範例：

```
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': {
                "Desk": 1,
                "length": { "$strLenCP": "$Desk" }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------