$ pencarian - Amazon DocumentDB

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

$ pencarian

Baru dari versi 5.0.

$searchOperator di Amazon DocumentDB digunakan untuk menyediakan kemampuan pencarian teks.

Parameter

Tidak ada

Contoh (MongoDB Shell)

Contoh berikut menunjukkan bagaimana menggunakan $search operator untuk melakukan query pencarian teks.

Buat dokumen sampel

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." } ]);

Contoh kueri

db.textcollection.find( { $text: { $search: "John" } } );

Keluaran

[ { _id: 1, name: 'John Doe', description: 'This is a sample document about John Doe.' } ]

Contoh kode

Untuk melihat contoh kode untuk menggunakan $search perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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()