

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# \$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 の両方の例では、MongoDB シェルの例と同様に、 `$substrCP`演算子を使用して `Desk`フィールドから状態の略語を抽出します。

------