在mongodb中有几种常见的索引,如Single Field Indexes/Compound Indexes/Multikey Indexes,另外还有什么Geospatial Indexes/Text Indexes/Hashed Index。
在工作中主要还是用到Single Field Indexes/Compound Indexes,Single Field Indexes就是对单一字段建立索引,Compound Indexes就是对多个字段建立组合索引。
单字段索引没什么太多要说的,主要是组合索引,查询的时候,语句必须是前缀模式:也就是建立索引的时候在第一个位置的字段必须出现,这样查询的才能用到索引。
Index prefixes are the beginning subsets of indexed fields. For example, consider the following compound index:
{ "item": 1, "location": 1, "stock": 1 }
The index has the following index prefixes:
{ item: 1 }
{ item: 1, location: 1 }
For a compound index, MongoDB can use the index to support queries on the index prefixes. As such, MongoDB can use the index for queries on the following fields:
- the
item
field, - the
item
field and thelocation
field, - the
item
field and thelocation
field and thestock
field.
MongoDB can also use the index to support a query on item
and stock
fields since item
field corresponds to a prefix. However, the index would not be as efficient in supporting the query as would be an index on onlyitem
and stock
.
However, MongoDB cannot use the index to support queries that include the following fields since without theitem
field, none of the listed fields correspond to a prefix index:
- the
location
field, - the
stock
field, or - the
location
andstock
fields.
If you have a collection that has both a compound index and an index on its prefix (e.g. { a: 1, b: 1 }
and { a: 1 }
), if neither index has a sparse or unique constraint, then you can remove the index on the prefix (e.g. { a: 1 }
). MongoDB will use the compound index in all of the situations that it would have used the prefix index.
需要注意的是: MongoDB can also use the index to support a query on item and stock fields since item field corresponds to a prefix. However, the index would not be as efficient in supporting the query as would be an index on only item and stock.
也就是说组合索引必须出现第一个位置的字段,后面位置如果是紧接着第一位置的话,这样两个字段都可以使用到索引,如果后面的字段和第一个索引位置的字段隔开了,则只有第一个索引字段可以用到索引,后面的字段全部都用不到索引了。