mongodb index related

    There are several common indexes in mongodb, such as Single Field Indexes/Compound Indexes/Multikey Indexes, and what are Geospatial Indexes/Text Indexes/Hashed Index.

    In the work, Single Field Indexes/Compound Indexes are mainly used. Single Field Indexes is to establish an index for a single field, and Compound Indexes is to establish a composite index for multiple fields.

    There is not much to say about a single-field index, mainly a composite index. When querying, the statement must be in prefix mode: that is, the field in the first position must appear when the index is created, so that the query can use the index.

 

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 the location field,
  • the item field and the location field and the stock 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 and stock fields.

If you have a collection that has both a compound index and an index on its prefix (e.g. and ), if neither index has a sparse or unique constraint, then you can remove the index on the prefix (e.g. ). MongoDB will use the compound index in all of the situations that it would have used the prefix index.{ a: 1, b: 1 }{ a: 1 }{ a: 1 }

 

    需要注意的是: 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.

   也就是说组合索引必须出现第一个位置的字段,后面位置如果是紧接着第一位置的话,这样两个字段都可以使用到索引,如果后面的字段和第一个索引位置的字段隔开了,则只有第一个索引字段可以用到索引,后面的字段全部都用不到索引了。

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326262486&siteId=291194637