

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# \$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"와 "star\$1rating"이 5인 텍스트 인덱스 필드가 있는 문서를 반환합니다.

## 코드 예제
<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()
```

------