翻译或纠错本页面

FAQ:索引

在某些情况下,索引不必 完全 加载到RAM,详细内容参见 只在内存中存储最近的数据的索引

How do I create an index?

要观察MongoDB是如何处理查询,在 mongo shell或在你使用的应用驱动中调用 explain()

注解

许多因素会决定你在哪些字段上建立索引,包括 selectivity ,内存适配,尽可能地在多个查询中重用索引,和支持给定查询中的所有字段。更详细的文档参见 /administration/indexes

How does an index build affect database performance?

任何改变索引中字段的写操作都会既修改文档本身也更新索引。如果你对文档的更新操作导致文档大小超出了已分配的记录大小,那么MongoDB不仅会修改这个文档,还会更新所有的索引。

To return information on currently running index creation operations, see Active Indexing Operations. To kill a running index creation operation, see db.killOp(). The partially built index will be deleted.

建立索引是一个IO密集型操作,特别是当你的集合很大的时候。包括MySQL在内的所有支持辅助索引的数据库系统都有这种情况。如果你需要在一个大集合上建立索引,可以考虑在后台建立它。参考 Index Build

如果你创建一个大索引而且没有选择在后台运行,这时如果导致数据库没有响应,可以按照如下方式解决:

How can I see if a query uses an index?

To inspect how MongoDB processes a query, use the explain() method.

How do I determine which fields to index?

你可以使用 min()max() 方法通过索引键来限制 find() 返回的游标的结果集。

How can I see the size of an index?

The db.collection.stats() includes an indexSizes document which provides size information for each index on the collection.

不完全可行。索引可以部分地支持这种查询,因为索引可以加快数组第一个元素的选择,但是不能用索引去比较数组中所有后续的元素,只能通过单独地扫描文档来完成。

使用命令 db.collection.stats() 可以检查集合上的索引所占空间大小。

How do write operations affect indexes?

Write operations may require updates to indexes:

  • 对于不需要对结果集进行排序的查询或范围查询,可以考虑创建一个字段,这个字段包含一个由文档组成的数组,数组中每一个文档都有一个保存指定类型属性的字段(比如 attrib )。你可以索引 attrib 字段。

  • When running with the MMAPv1 storage engine, if an update to a document causes the document to grow past its allocated record size, MongoDB moves the document to a new record and updates all indexes that refer to the document, regardless of the field modified.

Therefore, if your application is write-heavy, indexes might affect performance.