

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

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

Amazon DocumentDB 中的 \$1indexOfBytes 運算子用於根據字元的位元組位置，在字串中尋找子字串的起始索引。這在處理可能包含多位元組字元的文字資料時非常有用，例如在非 Latin 指令碼中找到的文字資料。

**參數**
+ `string`：要搜尋的輸入字串。
+ `substring`：要在輸入字串中搜尋的子字串。
+ `[<start>]`：（選用） 搜尋的開始位置 （以零為基礎）。如果未指定，搜尋會從字串開頭開始。

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

下列範例示範如何使用 在代表桌面位置的一組字串中`$indexOfBytes`尋找第一個連字號字元的索引。

**建立範例文件**

```
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: { stateLocation: { $indexOfBytes: ["$Desk", "-"] } } }
]);
```

**輸出**

```
{ "_id" : 1, "stateLocation" : 11 }
{ "_id" : 2, "stateLocation" : 6 }
{ "_id" : 3, "stateLocation" : 7 }
{ "_id" : 4, "stateLocation" : 8 }
```

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

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

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

  const result = await db.collection('people').aggregate([
    { $project: { stateLocation: { $indexOfBytes: ["$Desk", "-"] } } }
  ]).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(db.people.aggregate([
        { '$project': { 'stateLocation': { '$indexOfBytes': ['$Desk', '-'] } } }
    ]))
    print(result)
    client.close()

example()
```

------