$meta - Amazon DocumentDB
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

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

$meta

$meta运算符用于访问与当前查询执行相关的元数据。此运算符主要用于文本搜索操作,其中元数据可以提供有关匹配文档相关性的信息。

参数

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

示例(MongoDB 外壳)

以下示例演示如何使用$meta运算符检索与文本搜索查询相匹配的文档的文本搜索分数。

创建示例文档

db.documents.insertMany([ { _id: 1, title: "Coffee Basics", content: "Coffee is a popular beverage made from roasted coffee beans." }, { _id: 2, title: "Coffee Culture", content: "Coffee coffee coffee - the ultimate guide to coffee brewing and coffee preparation." }, { _id: 3, title: "Tea vs Coffee", content: "Many people prefer tea over coffee for its health benefits." } ]);

创建文本索引

db.documents.createIndex({ content: "text" });

查询示例

db.documents.find( { $text: { $search: "coffee" } }, { _id: 0, title: 1, content: 1, score: { $meta: "textScore" } } ).sort({ score: { $meta: "textScore" } });

输出

[ { title: 'Coffee Culture', content: 'Coffee coffee coffee - the ultimate guide to coffee brewing and coffee preparation.', score: 0.8897688388824463 }, { title: 'Coffee Basics', content: 'Coffee is a popular beverage made from roasted coffee beans.', score: 0.75990891456604 }, { title: 'Tea vs Coffee', content: 'Many people prefer tea over coffee for its health benefits.', score: 0.6079270839691162 } ]

代码示例

要查看使用该$meta命令的代码示例,请选择要使用的语言的选项卡:

Node.js
const { MongoClient } = require('mongodb'); async function findWithTextScore() { 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('documents'); const result = await collection.find( { $text: { $search: "coffee" } }, { projection: { _id: 0, title: 1, content: 1, score: { $meta: "textScore" } } } ).sort({ score: { $meta: "textScore" } }).toArray(); console.log(result); client.close(); } findWithTextScore();
Python
from pymongo import MongoClient 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['documents'] for doc in collection.find( {'$text': {'$search': 'coffee'}}, {'_id': 0, 'title': 1, 'content': 1, 'score': {'$meta': 'textScore'}} ).sort([('score', {'$meta': 'textScore'})]): print(doc) client.close()