Docs 菜单

Docs 主页开发应用程序MongoDB Manual

限制扫描的条目数

本教程介绍如何创建索引,以限制针对包含 $text表达式和相等条件的查询扫描的索引项数量。

集合 inventory 包含以下文档:

{ _id: 1, dept: "tech", description: "lime green computer" }
{ _id: 2, dept: "tech", description: "wireless red mouse" }
{ _id: 3, dept: "kitchen", description: "green placemat" }
{ _id: 4, dept: "kitchen", description: "red peeler" }
{ _id: 5, dept: "food", description: "green apple" }
{ _id: 6, dept: "food", description: "red potato" }

考虑按各个部门执行文本搜索的常见用例,例如:

db.inventory.find( { dept: "kitchen", $text: { $search: "green" } } )

要将文本搜索限制为仅扫描特定dept内的文档,请创建一个复合索引,该索引首先指定字段dept上的升序/降序索引键,然后指定字段description上的text索引键:

db.inventory.createIndex(
{
dept: 1,
description: "text"
}
)

然后,特定部门内的搜索将限制对已建立索引的文档的扫描。例如,以下查询仅扫描dept等于kitchen的文档:

db.inventory.find( { dept: "kitchen", $text: { $search: "green" } } )

注意

  • 复合text索引不能包含任何其他特殊索引类型,例如多键地理空间索引字段。

  • 如果复合text索引包含text索引键前面的键,要执行$text搜索,查询谓词必须包含前面键的等值匹配条件

  • 创建复合text索引时,所有text索引键必须在索引规范文档中相邻列出。

提示

另请参阅:

← 使用权重控制搜索结果