Learn the "why" behind slow queries and how to fix them in our 2-Part Webinar.
Register now >
Docs 菜单
Docs 主页
/ /

$text 查询

注意

MongoDB提供改进的全文搜索解决方案,MongoDB Search,和语义搜索解决方案,MongoDB Vector Search。我们建议使用 $search$searchMeta$vectorSearch 阶段,而不是 $text操作符。

要运行 $text 查询,您的集合必须具有文本索引。MongoDB提供文本索引来支持对字符串内容进行 $text 查询。文本索引可以包括值为string或string元素数组的任何字段。一个集合只能有一个文本索引,但该索引可以涵盖多个字段。

有关文本索引的完整参考,包括行为、分词和属性,请参阅“自管理部署上的文本索引”部分。

本示例演示了如何建立文本索引,并利用它查找仅有文本字段的咖啡店。

使用以下文档创建集合 stores

db.stores.insertMany(
[
{ _id: 1, name: "Java Hut", description: "Coffee and cakes" },
{ _id: 2, name: "Burger Buns", description: "Gourmet hamburgers" },
{ _id: 3, name: "Coffee Shop", description: "Just coffee" },
{ _id: 4, name: "Clothes Clothes Clothes", description: "Discount clothing" },
{ _id: 5, name: "Java Shopping", description: "Indonesian goods" },
{ _id: 6, name: "NYC_Coffee Shop", description: "local NYC coffee" }
]
)

mongosh 中运行以下命令以允许 $text 查询 namedescription 字段:

db.stores.createIndex( { name: "text", description: "text" } )

您可以用双引号将多词字符串括起来,以搜索精确的多词字符串。$text 查询仅匹配包含整个 string 的文档。

示例,以下查询可查找包含字符串“coffee shop”的所有文档:

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

此查询返回以下文档:

[
{ _id: 3, name: 'Coffee Shop', description: 'Just coffee' },
{ _id: 6, name: 'NYC_Coffee Shop', description: 'local NYC coffee' }
]

除非指定,否则精确字符串搜索不区分大小写或变音符号。 示例,以下查询返回与上一个查询相同的结果:

db.stores.find( { $text: { $search: "\"COFFEé SHOP\"" } } )

精确字符串搜索不处理词干提取或停用词。

要排除某个单词,可以在前面加上“-”字符。例如,要查找所有包含“java”或“shop”但不包含“coffee”的商店,请使用以下命令:

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

默认, MongoDB以未排序的顺序返回结果。 但是, $text查询会计算每个文档的相关性分数,该分数指定文档与查询的匹配程度。

要按相关性分数顺序对结果进行排序,您必须显式投影 $meta textScore 字段并按该字段进行排序:

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

$text 也可在聚合管道中使用。

后退

文本搜索(Text Search)

在此页面上