mongodb索引相关

    在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 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. { 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.

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值