限制扫描条目的数量
本教程描述了如何创建索引来限制对包含$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
上指定一个升序/降序索引键,然后在字段描述上指定一个文本索引键:
db.inventory.createIndex(
{
dept: 1,
description: "text"
}
)
然后,特定部门内的文本搜索将限制索引文档的扫描。例如,下面的查询只扫描那些dept = kitchen的文档:
db.inventory.find( { dept: "kitchen", $text: { $search: "green" } } )
[success] 注意
也可以看看
译者:杨帅