Home > Back-end >  In mongo, can you rebuild one single index?
In mongo, can you rebuild one single index?

Time:05-28

In mongo, you can rebuild all indexes with

db.collection.reIndex()

But is there a way to rebuild a single index?

Thanks, Kevin

CodePudding user response:

The db.collection.reIndex() drops all indexes on a collection and recreates them. This operation may be expensive for collections that have a large amount of data and/or a large number of indexes.

It's very costly operation and blocks all the operations on the collection for the duration.

You can do the same using removeIndex and then createIndex.

And 5.0 onwards, reIndex will be restricted to standalone instances.

CodePudding user response:

Identify all your indexes with:

db.collection.getIndexes();

Find the one you want to rebuild, e.g.:

    {
        "v" : 2,
        "key" : {
            "fld1" : 1,
            "fld2" : -1
        },
        "name" : "fld1_1_fld2_-1"
    }

"Safely" drop and rebuild with explicit specification instead of name:

var idx={fld1:1,fld2:-1};db.collection.dropIndex(idx);db.collection.createIndex(idx);
  • Related