Welcome to a tutorial on Indexing n MongoDB.
Indexes in SQL programming are special data structures 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.
Also, indexes are easily generated by making use of one or more columns of a given table. Note that the data structure used by an index is a Binary Tree (B-Tree).
Indexes play an important role in the efficient execution of the queries in MongoDB. Typically, if no index is defined in MongoDB, then it has to scan all the documents of a given collection. So, an index is used by MongoDB to reduce the number of documents to be scanned in a given collection.
More importantly, MongoDB's index is quite similar to the indexes used in other relational databases. Also, it defines the indexes at the collection level and supports indexing on any fields in a MongoDB collection.
A default index named _id is provided by MongoDB, which acts as a primary key to access any document in a collection. This _id index avoids the insertion of 2 documents with the same value for the _id field.
Run the command below to create an index in MongoDB.
db.collection_name.createIndex({field : value })
Now, to create an index on the field regNo for a student collection, run this command db.student.createIndex({regNo : 1})
The output of this command is shown below.
{
"createdCollectionAutomatically": false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
Also, we can create Index on multiple fields by running a single command: db.student.createIndex({regNo : 1, address : -1})
Index Type | Description |
Single field index | It is used to create an index on a single field and it can be user-defined as well apart from the default _id one. |
Compound index | This supports the user-defined indexes on multiple fields. |
Multi-key index | It uses multi-key indexes basically to store the arrays. MongoDB creates a separate index for each element in an array. It also intelligently identifies to create a multi-key index if the index contains elements from an array. |
Geospatial index | It is used to support the queries required for the geospatial coordinate data. |
Text index | It is used to search for string content in a collection |
Hashed index | This is used for hash-based Sharding |
Therefore, having all these features, index management is an important and central part of the MongoDB application.