

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

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

Amazon DocumentDB の `$substr`演算子は、特定の文字列から部分文字列を抽出するために使用されます。これは、バイトの範囲ではなく文字の範囲に基づいて部分文字列を定義する必要がある場合に特に便利です。これは、文字を表すために使用されるバイト数が異なる可能性がある Unicode 文字列を処理する場合に特に重要です。

**パラメータ**
+ `string`: 部分文字列を抽出する入力文字列。
+ `start`: 抽出する部分文字列の開始位置 (ゼロベース）。負以外の整数式にすることができます。
+ `length`: 抽出された部分文字列の文字数。負以外の整数式にすることができます。

## 例 (MongoDB シェル)
<a name="substr-examples"></a>

この例では、 を使用して従業員のデスクの場所から状態の略語を`$substr`抽出する方法を示します。

**サンプルドキュメントを作成する**

```
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": { $substr: ["$Desk", 12, 3] }
    }
  }
])
```

**出力**

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

## コードの例
<a name="substr-code"></a>

`$substr` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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

  const result = await collection.aggregate([
    {
      $project: {
        "state": { $substrCP: ["$Desk", 12, 3] }
      }
    }
  ]).toArray();

  console.log(result);
  await 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"]
    collection = db["people"]

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

    print(result)
    client.close()

example()
```

------