MongoDB Indexing: createIndex() & dropIndex()

⚡ Smart Summary

MongoDB indexes store an ordered subset of a collection’s fields so queries can locate documents without scanning every record. The createIndex, getIndexes, and dropIndex methods build, list, and remove these performance-critical structures.

  • 🚀 Purpose: Indexes let MongoDB skip full collection scans for faster reads.
  • 🛠️ createIndex: Builds single-field or compound indexes in ascending or descending order.
  • 🔍 getIndexes: Lists every index on a collection, including the default _id.
  • 🗑️ dropIndex: Removes one index; dropIndexes clears all except _id.
  • ⚖️ Trade-off: Too many indexes slow inserts, updates, and deletes.
  • 🤖 AI Tuning: Assistants recommend and generate the right indexes automatically.

MongoDB Indexing createIndex dropIndex

What are MongoDB Indexes?

Indexes are very important in any database, and with MongoDB it is no different. With the use of indexes, performing queries in MongoDB becomes more efficient.

If you had a collection with thousands of documents with no indexes, and then you query to find certain documents, then in such a case MongoDB would need to scan the entire collection to find the documents. But if you had indexes, MongoDB would use these indexes to limit the number of documents that had to be searched in the collection.

Indexes are special data sets which store a partial part of the collection’s data. Since the data is partial, it becomes easier to read this data. This partial set stores the value of a specific field, or a set of fields, ordered by the value of the field.

Understanding Impact of Indexes

Even though the introduction has shown that indexes are good for queries, having too many indexes can slow down other operations such as the Insert, Delete, and Update operations.

If there are frequent insert, delete, and update operations carried out on documents, then the indexes would need to change that often, which would just be an overhead for the collection.

The below example shows what field values could constitute an index in a collection. An index can either be based on just one field in the collection, or it can be based on multiple fields in the collection.

In the example below, the Employeeid “1” and EmployeeCode “AA” are used to index the documents in the collection. So when a query search is made, these indexes will be used to quickly and efficiently find the required documents in the collection.

So even if the search query is based on the EmployeeCode “AA”, that document would be returned.

Understanding Impact of Indexes

How to Create Indexes: createIndex()

Creating an index in MongoDB is done by using the createIndex method.

The following example shows how to add an index to a collection. Let us assume that we have our same Employee collection, which has the field names of “Employeeid” and “EmployeeName”.

Create Indexes with createIndex

db.Employee.createIndex({Employeeid:1})

Code Explanation:

  1. The createIndex method is used to create an index based on the “Employeeid” of the document.
  2. The “1” parameter indicates that when the index is created with the “Employeeid” field values, they should be sorted in ascending order. Please note that this is different from the _id field (which uniquely identifies each document) that MongoDB creates automatically. The documents will now be sorted as per the Employeeid and not the _id field.

If the command is executed successfully, the following output will be shown:

Output:

createIndex output

  1. The numIndexesBefore: 1 indicates the number of field values in the indexes before the command was run. Each collection has the _id field, which also counts as a field value, so numIndexesBefore is 1.
  2. The numIndexesAfter: 2 indicates the number of field values in the indexes after the command was run.
  3. The “ok: 1” output specifies that the operation was successful, and the new index is added to the collection.

The above code shows how to create an index based on one field value, but one can also create an index based on multiple field values. The following example shows how this can be done:

Create compound index on multiple fields

db.Employee.createIndex({Employeeid:1, EmployeeName:1})

The createIndex method now takes into account multiple field values, which will cause the index to be created based on the “Employeeid” and “EmployeeName”. The Employeeid:1 and EmployeeName:1 indicate that the index should be created on these two field values, with the :1 indicating ascending order. This is known as a compound index.

How to Find Indexes: getIndexes()

Finding an index in MongoDB is done by using the getIndexes method. The following example shows how this can be done:

Find Indexes with getIndexes

db.Employee.getIndexes()

The getIndexes method is used to find all of the indexes in a collection.

If the command is executed successfully, the following output will be shown:

Output:

getIndexes output

The output returns a document which shows that there are two indexes in the collection: the _id field and the Employeeid field. The :1 indicates that the field values in the index are created in ascending order.

How to Drop Indexes: dropIndex()

Removing an index in MongoDB is done by using the dropIndex method. The following example shows how this can be done:

Drop Indexes with dropIndex

db.Employee.dropIndex({Employeeid:1})

The dropIndex method takes the required field values which need to be removed from the index.

If the command is executed successfully, the following output will be shown:

Output:

dropIndex output

  1. The nIndexesWas: 3 indicates the number of field values in the indexes before the command was run. Each collection has the _id field, which also counts as a field value.
  2. The ok: 1 output specifies that the operation was successful, and the “Employeeid” field is removed from the index.

To remove all of the indexes at once in the collection, one can use the dropIndexes command. The following example shows how this can be done:

Drop all indexes with dropIndexes

db.Employee.dropIndexes()

The dropIndexes method will drop all of the indexes except for the _id index.

If the command is executed successfully, the following output will be shown:

Output:

dropIndexes output

  1. The nIndexesWas: 2 indicates the number of field values in the indexes before the command was run.
  2. Each collection has the _id field, which also counts as a field value and will not be removed by MongoDB; that is what this message indicates.
  3. The ok: 1 output specifies that the operation was successful.

FAQs

A single-field index sorts one field and suits queries filtering on that field alone. A compound index covers several fields in one structure and suits queries that filter or sort on those fields together. Compound indexes support up to 32 fields.

The _id field is MongoDB’s primary key, so every collection gets a unique _id index automatically. It cannot be dropped. That is why numIndexesBefore starts at 1 even before you add any custom index.

Run the query with .explain(“executionStats”). In the winning plan, an IXSCAN stage means an index was used, while a COLLSCAN means MongoDB scanned every document and a new index may help.

Use the $indexStats aggregation stage to see how often each index is accessed. Indexes with very low usage waste disk and slow writes, so remove them with dropIndex to keep the collection lean.

AI tools analyze slow query logs and suggest which fields to index. MongoDB’s Performance Advisor ranks index recommendations by impact, helping you add high-value indexes and skip redundant ones.

Yes. AI Copilot assistants turn plain-English requests into correct createIndex syntax, including ascending or descending keys and compound field order, then explain the resulting index.

ESR stands for Equality, Sort, Range. When building a compound index, place equality-match fields first, then sort fields, then range filters. This ordering lets MongoDB use the index most efficiently.

A covered query is answered entirely from an index, without reading the documents. When every field in the filter and the projection lives in one index, MongoDB returns results faster.

Summarize this post with: