翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
$search
バージョン 5.0 の新機能。
Amazon DocumentDB の $search演算子は、テキスト検索機能を提供するために使用されます。
パラメータ
なし
例 (MongoDB シェル)
次の例は、 $search演算子を使用してテキスト検索クエリを実行する方法を示しています。
サンプルドキュメントを作成する
db.textcollection.createIndex({"description": "text"});
db.textcollection.insertMany([
{ _id: 1, name: "John Doe", description: "This is a sample document about John Doe." },
{ _id: 2, name: "Jane Smith", description: "This is a sample document about Jane Smith." },
{ _id: 3, name: "Bob Johnson", description: "This is a sample document about Bob Johnson." },
{ _id: 4, name: "Jon Jeffries", description: "This is a sample document about Jon Jeffries." }
]);
クエリの例
db.textcollection.find(
{ $text: { $search: "John" } }
);
出力
[
{
_id: 1,
name: 'John Doe',
description: 'This is a sample document about John Doe.'
}
]
コードの例
$search コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。
- Node.js
-
const { MongoClient } = require('mongodb');
async function findWithText() {
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('textcollection');
const result = await collection.find(
{ $text: { $search: "John" } }
).sort({ score: { $meta: "textScore" } }).toArray();
console.log(result);
client.close();
}
findWithText();
- Python
-
from pymongo import MongoClient
def find_with_text():
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['textcollection']
result = list(collection.find(
{ '$text': { '$search': 'John' } }
))
print(result)
client.close()
find_with_text()