$meta - Amazon DocumentDB

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

$meta

$meta聚合运算符访问与聚合管道中的文档关联的元数据。它通常用于检索文本搜索分数和按相关性对结果进行排序。

参数

  • textScore:检索文本搜索分数,该分数表示文档与搜索查询的相关性。

示例(MongoDB 外壳)

以下示例演示了在聚合管道中使用$meta运算符来检索文本搜索分数并按文本搜索分数进行排序。

创建示例文档

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

查询示例

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

输出

[ { _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 } ]

代码示例

要查看使用$meta聚合运算符的代码示例,请选择要使用的语言的选项卡:

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