Skip to content

3.0 Indexing

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

3.0 Indexing

index chart

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 and 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

One index structure holds references to multiple fields (max 31) 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(s) 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 and fields be in the same order.

Indexing Replica Sets

Indexing replica sets involves stopping updates and indexing each replica at a time. In sharded clusters this process need to be repeated for each shard.

  • Stop a secondary and restart as standalone
  • Build index
  • Restart mongod as part of replica set/shard
  • Wait for restarted secondary to catch up on replication
  • Repeat for remaining members
  • Restart former primary as standalone
  • Build index
  • restart mongodb as part of replica set/shard
  • Wait for replication to catch up

More info here https://docs.mongodb.com/manual/tutorial/build-indexes-on-replica-sets/#index-building-replica-sets

Clone this wiki locally