$search - Amazon DocumentDB

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

$search

5.0 版的新功能。

Amazon DocumentDB 中的$search運算子用於提供文字搜尋功能。

參數

範例 (MongoDB Shell)

下列範例示範如何使用 $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()