Indexing in MongoDB
Indexes in SQL programming are nothing but a special data structure used to easily and quickly locate the record in a given table of the database without being required to traverse through each and every record of the table. Indexes are easily generated using one or more columns of a given table. As a note, the data structure used by an index is a Binary Tree (B-Tree).
In MongoDB, indexes plays a vital role in efficiently execution of the queries. Basically, if no index is defined in MongoDB, then it has to scan every document of a given collection. Hence, MongoDB uses index to reduce the number of documents to be scanned in a given collection. In fact, MongoDB's index is more or less similar to the indexes used in other relational databases.
The fact is that the MongoDB defines the indexes at the collection level and supports indexing on any fields in a MongoDB collection.
Default Index in MongoDB
Mongodb provides a default index named _id
which acts as a primary key to access any document in a collection. This _id
index basically avoids the insertion of 2 documents with the same value for the _id
field.
Creating an Index using createIndex()
To create an index in MongoDB, run the following command :
db.collection_name.createIndex({field : value })
To create an index on the field regNo
for a student collection, run the command db.student.createIndex({regNo : 1})
Following will be the output upon running the above command :
{
"createdCollectionAutomatically": false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
We can also create Index on multiple fields by running a single command. The command will be :
db.student.createIndex({regNo : 1, address : -1})
Types of Indexes in MongoDB
Index Type | Description |
Single field index | Used to create an index on a single field and it can be a user defined as well apart from the default _id one. |
Compound index | MongoDB supports the user-defined indexes on multiple fields. |
Multi key index | MongoDB uses multi key indexes basically to store the arrays. MongoDB creates a separate index for each element in an array. MongoDB intelligently identifies to create a multi key index if the index contains elements from an array. |
Geospatial index | Used to support the queries required for the geospatial coordinate data. |
Text index | This index is used to search for a string content in a collection |
Hashed index | Used for hash based Sharding |
Hence, with all the above features mentioned, Index management is the vital and central part of the MongoDB application.