In earlier posts on MongoDB, we saw the various multi-faceted advantages of MongoDB. We also compared MongoDB with MySQL and also DynamoDB. But did you realize till now what is that which causes MongoDB to perform so exceedingly well. Well, it is the indexing feature in MongoDB. So lets get rightaway with How MongoDB Index Works?

What are Indexes?

Indexes are there to usually purport the tidy execution of various queries run in MongoDB. Without the use of Indexing, MongoDB will have to perform a set scan wherein it has to go looking over documents, collection one after the other to finally arrive at the target search. Using Indexes, thus, MongoDB put a limit to the number of documents and/or collections it needs to look into.

Hence, indexes are special data structures which store some portion of the collections’ dataset to traverse. It stores values of the fields to search from.
The ordering of the index entries thus, supports efficient equality matches and range-based query operations. In extra to all these, MongoDB can also return sorted results by using ordering functions present within the index operations.

Diagram of a query that uses an index to select and return sorted results. The index stores ``score`` values in ascending order. MongoDB can traverse the index in either ascending or descending order to return sorted results.

Basically the indexes in any language are the same. Moreover, MongoDB defines these indexes at the gathering level and purports support to the indexes in the documents or in a MongoDB collection and/or its parts and sub-parts.

Here’s a quick overview of Sorting in MongoDB

The Default “_id” index

MongoDB builds a default index when creating a collection. This index then bars the users from inserting more than one documents having the same index field value.

In Sharded Clusters, though if no default _id index is used, then errors may occur. To prevent such errors, a standard self-generated ObjectId is used.

How to Create an Index

Now, that we are aware of what Indexes are lets get to see how to create an index ourselves.

Syntax :

# db.collection.createIndex( <key and index type specification>, <options> )
db.collection.createIndex( { age :  -1 } )
# The above command creates a single-key index in descending order on the age field.
How MongoDB Index Works

Note: MongoDB uses a B-Tree structure for Indexing.

Names for Indexes

The general names for Indexes are an amalgamation of the index keys and their direction. Lets take an example :

Suppose we create an index on  { roll : 1, course : -1 } then the index name stands as  roll_1_course_-1.

Though, you can also create custom name for an index as in :

db.products.createIndex(  { dept : 1, course : -1} ,  { name: "Course Details" })

This creates the index name as Course Details for dept : 1 and course : -1.

Types of Indexes

There are various types of indexes in MongoDB like Single Field Index, Compound Index and Multi-key Index. Lets discuss each one in details hereof.

Single Field Index

These are user-defined indexes where the type order of the index doesn’t matter as MongoDB is capable of traversing in either direction.

Diagram of an index on the ``score`` field (ascending).

The Compound Index

As well as it supports Single Field user-defined indexes, MongoDB in turn, supports multiple fields user-defined indexes also. These are known as the Compound Indexes. The order of the fields in the compound index holds importance. Because it is the same order in which the index sorts itself.

db.products.createIndex(  { dept : 1, course : -1} ,  { name: "Course Details" })

In this example, the Index first sorts itself in ascending order of the department and then within each department it sorts in the descending order of the course.

Multi-key Index

MongoDB also facilitates the use of Multi-key Indexes. These indexes store the content contained in the arrays. That is when an array field is indexed, MongoDB by itself create another separate set of indexes for each element of the array. This allows the various queries to search and select documents containing the arrays by matching on elements in the arrays.

Diagram of a multikey index on the ```` field. The ``addr`` field contains an array of address documents. The address documents contain the ``zip`` field.

Collations and Index — How MongoDB Index Works

Collation is there to facilitate the users to provide lexicographic rules for string comparison. These can be the rules for letter cases or maybe for accent marks and thereof.

While using an index for comparing strings, the same collation must also be specified. Because one index and another collation together are not compatible. Both need to be the same for compatibility and hence the comparison to happen.

Lets see for example, a collection by the name Coll has an index on the string field by the name “category” and the Collation locale is “en”

db.Coll.createIndex( { category: 1 }, { collation: { locale: "en" } } )

The query operation that follows can specify the index as it is mentioning the same collation.

db.Coll.find( { category: "malls" } ).collation( { locale: "en" } )

However, another query operation, which doesn’t use the same collation or maybe just uses the simple binary collator. It cannot make use of the index :

db.Coll.find( { category: "malls" } )

Note: For compound indexes wherein an operation mentioning another collation may be able to use the index to purport comparisons on the prefix-index keys.

Suppose to say, the “Coll” collection has a compound index on two numeric fields ratings and price and also on the category string field. An index is then built with with the collation locale “en” to compare the strings. As in,

db.Coll.createIndex(   { ratings : 1, price: -1, category: 1 },   { collation: { locale: "en" } } )
How MongoDB Index Works

Jotting It Down -> How MongoDB Index Works

In this article we got ourselves fully familiar with indexes. What are indexes? What are Collations? And, also what are Index Names? How to create and Use them? The different types of Indexes in MongoDB. And also the use of Indexing and Collation together. We have seen all these through ample examples to make the concepts clear. Hope this post goes a long way in helping you out !!!

Categorized in: