Last Updated: 08 August, 2023
Indexes are special data structures that can store collection's data set in a form that is easy to traverse. Queries are efficiently executed with the help of indexes in MongoDB.
Indexes help MongoDB find documents that match the query criteria without performing an entire collection scan. If a query has an appropriate index, MongoDB uses the index and limits the number of documents it examines. Indexes store field values in the order of the value. The order in which the index entries are made support operations, such as equality matches and range-based queries. MongoDB sorts and returns the results by using the sequential order of the indexes.
Indexes improve the speed of search operations in database because instead of searching the whole document, the search is performed on the indexes that holds only few fields.
Note: having too many indexes can slow down insert, update, and delete operations due to the increased write and data space required by indexes.
MongoDB automatically creates a unique index on the _id field when we create a collection. Clients are prohibited from inserting two documents with the same _id field value. We are unable to remove this index on the _id field in MongoDB.
At the time of creating an Index in MongoDB, we can give some meaningful name to the index, but if we do not specify any name, MongoDB gives the default name of the index as the concatenation of the indexed keys and each key's direction in the index (i.e., 1 or -1) using underscores as a separator. For example, an index created on { item : 1, quantity: -1 } has the name item_1_quantity_-1.
To create an index in MongoDB Shell, we use db.collection.createIndex() method. Let's see the syntax and example below:
Syntax:
db.collection.createIndex( <key and index type specification>, <options> )
Example:
db.collection.createIndex( { emp_id: -1 } )
Finding all Indexes in a collection.
db.employee.getIndexes()
Here, employee is a collection name, and the getIndexes() method is used to find all of the indexes in an employee collection.
MongoDB has many different types of indexes to serve different kinds of data and queries.
Single Field Index
In MongoDB, an index is referred to as a single Field Index if it is created on just one field of a document.
Example:
db.collection.createIndex( { emp_id: -1 } )
Compound Index
MongoDB allows us to create an index on more than one field of a document; this type of index is known as a compound index.
A compound index's field listing order is important. For instance, if a compound index has the following values: emp_id: 1, data_of_joining: -1, the index first sorts by emp_id before sorting by date_of_joining within each emp_id value.
Example:
db.collection.createIndex( { emp_id: 1, date_of_joining: -1 } )
Reference: https://www.mongodb.com/docs/manual/indexes/
That's all, guys. I hope this MongoDB article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com