本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$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聚合运算符的代码示例,请选择要使用的语言的选项卡: