$meta - Amazon DocumentDB

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

$meta

Operator $meta agregasi mengakses metadata yang terkait dengan dokumen dalam pipeline agregasi. Hal ini biasanya digunakan untuk mengambil skor pencarian teks dan mengurutkan hasil berdasarkan relevansi.

Parameter

  • textScore: Mengambil skor pencarian teks yang menunjukkan relevansi dokumen dengan permintaan pencarian.

Contoh (MongoDB Shell)

Contoh berikut menunjukkan penggunaan $meta operator dalam pipeline agregasi untuk mengambil dan mengurutkan berdasarkan skor pencarian teks.

Buat dokumen sampel

db.articles.createIndex({ content: "text" }); db.articles.insertMany([ { _id: 1, title: "Python Programming", content: "Python is a versatile programming language used for web development." }, { _id: 2, title: "Python Guide", content: "Learn Python programming with Python tutorials and Python examples." }, { _id: 3, title: "Java Basics", content: "Java is another popular programming language." } ]);

Contoh kueri

db.articles.aggregate([ { $match: { $text: { $search: "Python" } } }, { $addFields: { score: { $meta: "textScore" } } }, { $sort: { score: -1 } } ]);

Keluaran

[ { _id: 2, title: 'Python Guide', content: 'Learn Python programming with Python tutorials and Python examples.', score: 1.5 }, { _id: 1, title: 'Python Programming', content: 'Python is a versatile programming language used for web development.', score: 0.75 } ]

Contoh kode

Untuk melihat contoh kode untuk menggunakan operator $meta agregasi, pilih tab untuk bahasa yang ingin Anda gunakan:

Node.js
const { MongoClient } = require('mongodb'); async function example() { 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('articles'); const result = await collection.aggregate([ { $match: { $text: { $search: "Python" } } }, { $addFields: { score: { $meta: "textScore" } } }, { $sort: { score: -1 } } ]).toArray(); console.log(result); await client.close(); } example();
Python
from pymongo import MongoClient def example(): 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['articles'] result = list(collection.aggregate([ { '$match': { '$text': { '$search': 'Python' } } }, { '$addFields': { 'score': { '$meta': 'textScore' } } }, { '$sort': { 'score': -1 } } ])) print(result) client.close() example()