

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

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

5.0 版的新功能。

Elastic 叢集不支援。

Amazon DocumentDB 中的`$regexFind`運算子用於對文件中的字串欄位執行規則運算式比對。它可讓您搜尋和擷取符合指定規則表達式模式的特定子字串。

**參數**
+ `input`：要搜尋的字串欄位或表達式。
+ `regex`：要比對的規則表達式模式。
+ `options`：（選用） 指定規則表達式選用參數的物件，例如區分大小寫和多行比對。支援的選項為 `i`（不區分大小寫） 和 `m`（多行）。

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

下列範例示範如何使用 `$regexFind`運算子來搜尋 `name` 欄位符合特定規則表達式模式的文件。

**建立範例文件**

```
db.users.insertMany([
  { "_id": 1, name: "John Doe", email: "john@example.com" },
  { "_id": 2, name: "Diego Ramirez", email: "diego@example.com" },
  { "_id": 3, name: "Alejandro Rosalez", email: "alejandro@example.com" },
  { "_id": 4, name: "Shirley Rodriguez", email: "shirley@example.com" }
]);
```

**查詢範例**

```
db.users.aggregate([
  {
    $project: {
      names: {
        $regexFind: { input: '$name', regex: 'j', options: 'i' }
      }
    }
  },
  { $match: {names: {$ne: null}}}
])
```

此查詢將傳回 `name` 欄位包含字母 "j" （不區分大小寫） 的所有文件。

**輸出**

```
[
  { _id: 1, names: { match: 'J', idx: 0, captures: [] } }
]
```

**注意：**如果您的查詢使用 Amazon DocumentDB 規劃器第 1 版，您必須使用提示來使用索引。如果沒有提示，查詢可能會執行集合掃描。若要檢查您的規劃器版本並進一步了解如何使用提示，請參閱 【Amazon DocumentDB 查詢規劃器文件】(https://docs.aws.amazon.com/documentdb/latest/developerguide/query-planner.html：//)。

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

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

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

```
const { MongoClient } = require('mongodb');

async function main() {
  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 users = db.collection('users');

  const results = await users.aggregate([
    { $project: { names: { $regexFind: { input: "$name", regex: "john", options: "i" }}}},
    { $match: {names: {$ne: null}}}
  ]).toArray();
  

  console.log(results);

  await client.close();
}

main();
```

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

```
from pymongo import MongoClient

client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
users = db['users']

results = list(users.aggregate([
    { "$project": { "names": { "$regexFind": { "input": "$name", "regex": "john", "options": "i" }}}},
    { "$match": {"names": {"$ne": None}}}
]))

print(results)

client.close()
```

------