为什么默认情况下将索引应用于特定列而不是应用于每个列?

时间:2018-09-19 07:50:43

标签: mongodb indexing

我已经阅读了有关在数据库中建立索引的信息,我不明白的是,为什么我们需要为特定的列指定索引,如果它使搜索快速,为什么默认情况下却不对所有列进行索引呢?是否可以在一个表中创建多个索引?

2 个答案:

答案 0 :(得分:1)

如果没有n。索引,并且当您执行任何修改键的保存/更新操作时,它将执行n次,因此会产生过多的写锁定。当您执行这样的操作时,您会发现没有索引的读取要比尝试使用过多索引进行一致更新的读取速度更快。因此,为了执行索引编制,您应该跟踪索引,否则会遇到很大的性能问题(RAM的浪费和写锁定)。

答案 1 :(得分:1)

To resume :

Using indexes improves performances on read query, because mongodb doesn't read entire collection when searching documents. It also improves sorting.

But these improvments have a cost :

  • Indexes use disk/memory space.
  • Delete, insert and update operations will be longer : on each insert, delete or update operation, mongodb must update all you concerned indexes.
  • There are multiple indexes type, and some of them (compound index ie) can have planty of combinations

For these reasons (but not only), by default only index on _id field (as it need to be unique) is created on collection creation.