This tutorial describes how to create indexes to limit the number of index entries scanned for queries that includes a 本教程介绍如何创建索引,以限制针对包含$text
expression and equality conditions.$text
表达式和相等条件的查询扫描的索引项的数量。
A collection inventory
contains the following documents: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" }
Consider the common use case that performs text searches by individual departments, such as:考虑按单个部门执行文本搜索的常见用例,例如:
db.inventory.find( { dept: "kitchen", $text: { $search: "green" } } )
To limit the text search to scan only those documents within a specific 要将文本搜索限制为仅扫描特定dept
, create a compound index that first specifies an ascending/descending index key on the field dept
and then a text
index key on the field description
:dept
内的那些文档,请创建一个复合索引,首先在字段dept
上指定升序/降序索引键,然后在字段description
上指定text
索引键:
db.inventory.createIndex( { dept: 1, description: "text" } )
Then, the text search within a particular department will limit the scan of indexed documents. 然后,特定部门内的文本搜索将限制索引文档的扫描。For example, the following query scans only those documents with 例如,以下查询仅扫描dept
equal to kitchen
:dept
等于kitchen
的文档:
db.inventory.find( { dept: "kitchen", $text: { $search: "green" } } )
text
index cannot include any other special index types, such as multi-key or geospatial index fields.text
索引不能包括任何其他特殊索引类型,如多键索引字段或地理空间索引字段。text
index includes keys preceding the text
index key, to perform a $text
search, the query predicate must include equality match conditions on the preceding keys.text
索引包含文本索引键之前的键,则要执行$text
搜索,查询谓词必须在前面的键上包含相等匹配条件。text
index, all text
index keys must be listed adjacently in the index specification document.text
索引时,索引规范文档中必须相邻列出所有text
索引键。