

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

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

`$text` 演算子は、ドキュメントコレクション内のテキストインデックス付きフィールドに対して全文検索を実行するために使用されます。この演算子を使用すると、特定の単語やフレーズを含むドキュメントを検索し、他のクエリ演算子と組み合わせて、追加の条件に基づいて結果をフィルタリングできます。

**パラメータ**
+ `$search`: 検索するテキスト文字列。

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

次の例は、 `$text`演算子を使用して「interest」という単語を含むドキュメントを検索し、「star\$1rating」フィールドに基づいて結果をフィルタリングする方法を示しています。

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

```
db.test.insertMany([
  { "_id": 1, "star_rating": 4, "comments": "apple is red" },
  { "_id": 2, "star_rating": 5, "comments": "pie is delicious" },
  { "_id": 3, "star_rating": 3, "comments": "apples, oranges - healthy fruit" },
  { "_id": 4, "star_rating": 2, "comments": "bake the apple pie in the oven" },
  { "_id": 5, "star_rating": 5, "comments": "interesting couch" },
  { "_id": 6, "star_rating": 5, "comments": "interested in couch for sale, year 2022" }
]);
```

**テキストインデックスを作成する**

```
db.test.createIndex({ comments: "text" });
```

**クエリの例**

```
db.test.find({$and: [{star_rating: 5}, {$text: {$search: "interest"}}]})
```

**出力**

```
{ "_id" : 5, "star_rating" : 5, "comments" : "interesting couch" }
{ "_id" : 6, "star_rating" : 5, "comments" : "interested in couch for sale, year 2022" }
```

上記のコマンドは、任意の形式の「interest」と 5 に等しい「star\$1rating」を含むテキストインデックス付きフィールドを持つドキュメントを返します。

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

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

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

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

async function searchDocuments() {
  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('test');

  const result = await collection.find({
    $and: [
      { star_rating: 5 },
      { $text: { $search: 'interest' } }
    ]
  }).toArray();

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

searchDocuments();
```

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

```
from pymongo import MongoClient

def search_documents():
    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.test

    result = list(collection.find({
        '$and': [
            {'star_rating': 5},
            {'$text': {'$search': 'interest'}}
        ]
    }))

    print(result)
    client.close()

search_documents()
```

------