Flat 10% & upto 50% off + Free additional Courses. Hurry up!



Indexes provide high performance read operations for frequently used queries. It includes indexes in MongoDB, describes the types and configuration options for indexes, and describes special types of indexing MongoDB supports. The section also provides tutorials detailing procedures and operational concerns, and providing information on how applications may use indexes.


8.1 Index Introduction

 Indexes support the efficient execution of queries in MongoDB.Without indexes, MongoDB must perform a collection scan, i.e. scan every document in a collection, to select those documents that match the query statement. If an appropriate index exists for a query, MongoDB can use the index to limit the number of documents it must inspect.

Indexes are special data structures that store a small portion of the collection’s data set in an easy to traverse form. The index stores the value of a specific field or set of fields, ordered by the value of the field. The ordering of the index entries supports efficient equality matches and range-based query operations. In addition, MongoDB can return sorted results by using the ordering in the index.


The following diagram illustrates a query that selects and orders the matching documents using an index:




8.1.1 Index Properties

  • Unique Indexes – The unique property for an index causes MongoDB to reject duplicate values for the indexed field. Other than the unique constraint, unique indexes are functionally interchangeable with other MongoDB indexes.
  • Sparse Indexes – The sparse property of an index ensures that the index only contain entries for documents that have the indexed field. The index skips documents that do not have the indexed field.
  • TTL Indexes – TTL indexes are special indexes that MongoDB can use to automatically remove documents from a collection after a certain amount of time.


8.2 Index Concepts

8.2.1 Index Types

MongoDB provides a number of different index types. You can create indexes on any field or embedded field within a document or embedded document. In the mongo shell, you can create an index by calling the createIndex() method.

  • Single Field Indexes – A single field index only includes data from a single field of the documents in a collection. MongoDB supports single field indexes on fields at the top level of a document and on fields in sub-documents.
  • Compound Indexes– A compound index includes more than one field of the documents in a collection.
  • Multikey Indexes – A multikey index is an index on an array field, adding an index key for each value in the array.
  • Geospatial Indexes and Queries – Geospatial indexes support location-based searches on data that is stored as either GeoJSON objects or legacy coordinate pairs.
  • Text Indexes – Text indexes support search of string content in documents.
  • Hashed Index – Hashed indexes maintain entries with hashes of the values of the indexed field and are primarily used with sharded clusters to support hashed shard keys.


8.2.2 Index Intersection

MongoDB can use the intersection of multiple indexes to fulfill queries. In general, each index intersection involves two indexes; however, MongoDB can employ multiple/nested index intersections to resolve a query.

To illustrate index intersection, consider a collection orders that has the following indexes:

{ qty: 1 }

{ item: 1 }

MongoDB can use the intersection of the two indexes to support the following query:

db.orders.find( { item: "abc123", qty: { $gt: 15 } } )

To determine if MongoDB used index intersection, run explain(); the results of explain() will include either an AND_SORTED stage or an AND_HASH stage


8.3 Indexing Tutorials

Indexes allow MongoDB to process and fulfill queries quickly by creating small and efficient representations of the documents in a collection.


8.3.1 Index Creation Tutorials

  •  Create an Index on a Single Field

 To create an index, use createIndex() or a similar method from your driver. The createIndex() method only creates an index if an index of the same specification does not already exist.

For example, the following operation creates an index on the userid field of the records collection:

db.records.createIndex( { userid: 1 } )

The value of the field in the index specification describes the kind of index for that field. For example, a value of 1 specifies an index that orders items in ascending order. A value of -1 specifies an index that orders items in descending order.

The created index will support queries that select on the field userid, such as the following:

db.records.find( { userid: 2 } )

db.records.find( { userid: { $gt: 10 } } )

But the created index does not support the following query on the profile_url field:

db.records.find( { profile_url: 2 } )

For queries that cannot use an index, MongoDB must scan all documents in a collection for documents that match the query.


  • Create a Compound Index

To create a compound index use an operation that resembles the following prototype:

db.collection.createIndex( { a: 1, b: 1, c: 1 } )

The value of the field in the index specification describes the kind of index for that field. For example, a value of 1 specifies an index that orders items in ascending order. A value of -1 specifies an index that orders items in descending order. For additional index types, see Index Types.


The following operation will create an index on the item, category, and price fields of the products collection:

db.products.createIndex( { item: 1, category: 1, price: 1 } )


  • Create a Unique Index on a single field

To create a unique index, consider the following prototype:

db.collection.createIndex( { a: 1 }, { unique: true } )

For example, you may want to create a unique index on the “tax-id” field of the accounts collection to prevent storing multiple account records for the same legal entity:

db.accounts.createIndex( { "tax-id": 1 }, { unique: true } )

The _id index is a unique index. In some situations you may consider using the _id field itself for this kind of data rather than using a unique index on another field.


  • Create a Sparse Index

Sparse indexes are like non-sparse indexes, except that they omit references to documents that do not include the indexed field. For fields that are only present in some documents sparse indexes may provide a significant space savings.


To create a sparse index on a field, use an operation that resembles the following prototype:

db.collection.createIndex( { a: 1 }, { sparse: true } )


The following operation, creates a sparse index on the users collection that only includes a document in the index if the twitter_name field exists in a document.

db.users.createIndex( { twitter_name: 1 }, { sparse: true } )

The index excludes all documents that do not include the twitter_name field.


  • Create a Hashed Index

Hashed indexes compute a hash of the value of a field in a collection and index the hashed value. These indexes permit equality queries and may be suitable shard keys for some collections. To create a hashed index specify hashed as the value of the index key, as in the following example:


Specify a hashed index on _id

db.collection.createIndex( { _id: "hashed" } )


  • Build Indexes on Replica Sets – To build indexes on a replica set, you build the indexes separately on the primary and the secondaries.


  • Build Indexes in the Background – Background index construction allows read and write operations to continue while building the index, but take longer to complete and result in a larger index.

To create an index in the background, add the background argument to the createIndex() operation, as in the following index:

db.collection.createIndex( { a: 1 }, { background: true } )


  • Build Old Style Indexes – A {v : 0} index is necessary if you need to roll back from MongoDB version 2.0 (or later) to MongoDB version 1.8.

Suppose you rolled back from MongoDB 2.0 to MongoDB 1.8, and suppose you had the following index on the items collection:

{ "v" : 1, "key" : { "name" : 1 }, "ns" : "mydb.items", "name" : "name_1" }

The v field tells you the index is a {v:1} index, which is incompatible with version 1.8. To drop the index, issue the following command:

db.items.dropIndex( { name : 1 } )

To recreate the index as a {v:0} index, issue the following command: { name : 1 } , { v : 0 } )


8.3.2 Index Management Tutorials

Instructions for managing indexes and assessing index performance and use.

  • Remove Indexes – Drop an index from a collection.
  • Modify an Index – Modify an existing index.
  • Rebuild Indexes – In a single operation, drop all indexes on a collection and then rebuild them.
  • Manage In-Progress Index Creation – Check the status of indexing progress, or terminate an ongoing index build.
  • Return a List of All Indexes – Obtain a list of all indexes on a collection or of all indexes on all collections in a database.
  • Measure Index Use – Study query operations and observe index use for your database.


8.3.3 Geospatial Index Tutorials

Instructions for creating and querying 2d, 2dsphere, and haystack indexes.

  • Create a 2dsphere Index – A 2dsphere index supports data stored as both GeoJSON objects and as legacy coordinate pairs.
  • Query a 2dsphere Index – Search for locations within, near, or intersected by a GeoJSON shape, or within a circle as defined by coordinate points on a sphere.
  • Create a 2d Index – Create a 2d index to support queries on data stored as legacy coordinate pairs.
  • Query a 2d Index – Search for locations using legacy coordinate pairs.
  • Create a Haystack Index – A haystack index is optimized to return results over small areas. For queries that use spherical geometry, a 2dsphere index is a better option.
  • Query a Haystack Index – Search based on location and non-location data within a small area.
  • Calculate Distance Using Spherical Geometry – Convert distances to radians and back again.


  • 8.3.4 Text Search Tutorials

Instructions for enabling MongoDB’s text search feature, and for building and configuring text indexes.

  • Create a text Index – A text index allows searches on text strings in the index’s specified fields.
  • Specify a Language for Text Index –The specified language determines the list of stop words and the rules for Text Search’s stemmer and tokenizer.
  • Specify Name for text Index – Override the text index name limit for long index names.
  • Control Search Results with Weights – Give priority to certain search values by denoting the significance of an indexed field relative to other indexed fields.
  • Limit the Number of Entries Scanned – Create an index to support queries that includes $text expressions and equality conditions.
  • Text Search in the Aggregation Pipeline – Perform various text search in the aggregation pipeline.

Learn more about Cassandra Versus MongoDB in this insightful blog now!

"0 Responses on Indexes"

Leave a Message

100% Secure Payments. All major credit & debit cards accepted Or Pay by Paypal.

Sales Offer

  • To avail this offer, enroll before 19th January 2017.
  • This offer cannot be combined with any other offer.
  • This offer is valid on selected courses only.
  • Please use coupon codes mentioned below to avail the offer

Sign Up or Login to view the Free Indexes.