Skip to content

3.0 Indexing

Olga Arsenieva edited this page Nov 21, 2018 · 33 revisions

3.0 Indexing

Function

Indexes improve query execution by storing a portion of the collection in a small B-tree collection that can be searched quickly, and saves query execution time by avoiding collection scan where all records in the collection are scanned.

How to use

A default _id index field is automatically generated by MongoDB when a new document is added and uniquely identifies all documents in a collection, and cannot be removed. An _id can be used as shard key in sharded clusters, or can be replaced by ObjectId.

To create an index use command which will only work if the index does not already exist:

db.<collectionname>.createIndex(< index key and type >, <options> )

The process of building indices heavily impacts the database and prevents read and write operations. To avoid this impact index construction can be run in the background using Background Construction.

To remove an index use the following command:

db.<collectionname>.dropIndex(< index key and type >)

or

db.<collectionname>.dropIndexes()

To see indexes associated with collection:

db.<collectionname>.getIndexes()

Single Field Index: Embedded field index vs embedded document index

Indexes can be created in embedded fields as well as embedded documents. An index on an embedded field can be created using a dot notation on a top level field and will support queries that search embedded document fields.

db.<abstract_collection>.createIndex( { "location.city":1 } )

An index on an embedded document indexes the entire document and returns results that match exactly, including all the fields and the order.

examples: https://docs.mongodb.com/manual/core/index-single/

Compound Index

compound index

One index structure holds references to multiple fields (max 32) and supports queries that match on multiple fields.

db.<collectionname>.createIndex( { <field1>: <type>, <field2>: <type2, ... } )

Index will sort fields based on the order they are listed in. Index prefix is the first field listed in the create statement. Index will support queries that do not search all the fields it sorts by, but prefix(the very first field) must be included in query and fields be in the same order.

Multikey Index

Created automatically if one of the fields being indexed is an array. Does not support multiple array fields in one index.

Index Intersection

Index intersection is the use of multiple indexes to support queries. Index intersection can support more queries than a compound index can because it is not limited by prefixes.