Note
This page describes text query capabilities for self-managed (non-Atlas) deployments. For data hosted on MongoDB, MongoDB also offers an improved full-text query solution, MongoDB Search and a vector search solution, Vector Search.本页介绍自我管理(非Atlas)部署的文本查询功能。对于托管在MongoDB上的数据,MongoDB还提供了改进的全文查询解决方案MongoDB搜索和矢量搜索解决方案矢量搜索。
Query Framework查询框架
Use the 使用$text query operator to perform text searches on a collection with a text index.$text查询运算符对具有text索引的集合执行文本搜索。
$text tokenizes the search string using whitespace and most punctuation as delimiters, and perform a logical OR of all such tokens in the search string.$text使用空格和大多数标点符号作为分隔符对搜索字符串进行标记,并对搜索字符串中的所有此类标记执行逻辑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.$sort阶段使用$meta聚合运算符。
For more information and examples, see $text in the Aggregation Pipeline on Self-Managed Deployments.有关更多信息和示例,请参阅自我管理部署聚合管道中的$text。
For data hosted on MongoDB, MongoDB Search provides the $search aggregation stage to perform full-text search on your collections.对于托管在MongoDB上的数据,MongoDB搜索提供了$Search聚合阶段,可以对集合执行全文搜索。