Docs HomeMongoDB Manual

Text Search Operators (Self-Managed Deployments)文本搜索运算符(自我管理部署)

Note

This page describes text search capabilities for self-managed (non-Atlas) deployments. 本页介绍了用于自我管理(非Atlas)部署的文本搜索功能。For data hosted on MongoDB Atlas, MongoDB offers an improved full-text search solution, Atlas Search.对于托管在MongoDB Atlas上的数据,MongoDB提供了一个改进的全文搜索解决方案Atlas search

Query Framework查询框架

Use the $text query operator to perform text searches on a collection with a text index.使用$text查询运算符可以对具有文本索引的集合执行文本搜索。

$text will tokenize the search string using whitespace and most punctuation as delimiters, and perform a logical OR of all such tokens in the search string.将使用空白和大多数标点符号作为分隔符来标记搜索字符串,并对搜索字符串中的所有此类标记执行逻辑OR。

For example, you could use the following query to find all stores containing any terms from the list "coffee", "shop", and "java" in the stores collection:例如,您可以使用以下查询来查找包含stores集合中“coffee”、“shop”和“java”列表中任何术语的所有库存:

db.stores.find( { $text: { $search: "java coffee shop" } } )

Use the $meta query operator to obtain and sort by the relevance score of each matching document. For example, to order a list of coffee shops in order of relevance, run the following:使用$meta查询运算符可以获得每个匹配文档的相关性得分并进行排序。例如,要按相关顺序订购咖啡店列表,请运行以下操作:

db.stores.find(
{ $text: { $search: "coffee shop cake" } },
{ score: { $meta: "textScore" } }
).sort( { score: { $meta: "textScore" } } )

For more information on the $text and $meta operators, including restrictions and behavior, see:有关$text$meta运算符的更多信息,包括限制和行为,请参阅:

Aggregation Pipeline聚合管道

When working with aggregation pipelines, use $match with a $text expression to execute a text search query. 使用聚合管道时,请将$match$text表达式一起使用,以执行文本搜索查询。To sort the results in order of relevance score, use the $meta aggregation operator in the $sort stage [1].要按相关性得分的顺序对结果进行排序,请在$sort阶段使用$meta聚合运算符[1]

For more information and examples of text search in Aggregation Operations pipelines, see Text Search in the Aggregation Pipeline.有关聚合操作管道中文本搜索的更多信息和示例,请参阅聚合管道中的文本搜索

For data hosted on MongoDB Atlas, Atlas Search provides the $search aggregation stage to perform full-text search on your collections.对于MongoDB Atlas上托管的数据,Atlas Search提供了$search聚合阶段,用于对您的集合执行全文搜索。

[1] The behavior and requirements of the $meta projection operator differ from that of the $meta aggregation operator. $meta投影运算符的行为和要求与$meta聚合运算符不同。For details on the $meta aggregation operator, see the $meta aggregation operator reference page.有关$meta聚合运算符的详细信息,请参阅$meta聚合运算符参考页。