Rebuilding indexes in MongoDB?


To rebuild indexes, use reIndex(). Let us first create an index. Following is the query −

> db.demo42.createIndex({"StudentFirstName":1});

This will produce the following output −

{
   "createdCollectionAutomatically" : true,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}

Following is the query to rebuild index in MongoDB −

> db.demo42.reIndex({"StudentFirstName":1});

This will produce the following output −

{
   "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
}

Updated on: 03-Apr-2020

467 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements