Rebuilding indexes in MongoDB?

To rebuild indexes in MongoDB, use the reIndex() method. This operation rebuilds all indexes on a collection, which can help resolve index corruption or optimize index performance after significant data changes.

Syntax

db.collection.reIndex()

Create Sample Index

Let us first create an index to demonstrate the rebuilding process ?

db.demo42.createIndex({"StudentFirstName": 1})
{
   "createdCollectionAutomatically" : true,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}

Rebuild All Indexes

Following is the query to rebuild all indexes in the collection ?

db.demo42.reIndex()
{
   "nIndexesWas" : 2,
   "nIndexes" : 2,
   "indexes" : [
      {
         "v" : 2,
         "key" : {
            "_id" : 1
         },
         "name" : "_id_",
         "ns" : "web.demo42"
      },
      {
         "v" : 2,
         "key" : {
            "StudentFirstName" : 1
         },
         "name" : "StudentFirstName_1",
         "ns" : "web.demo42"
      }
   ],
   "ok" : 1
}

Key Points

  • reIndex() rebuilds all indexes on the collection, including the default _id index.
  • This operation blocks all read and write operations on the collection during execution.
  • Use sparingly, as it can be resource-intensive on large collections.

Conclusion

The reIndex() method rebuilds all indexes in a collection, helping resolve corruption issues and optimize performance. Use it cautiously as it blocks collection access during execution.

Updated on: 2026-03-15T02:48:22+05:30

683 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements