How to Get All Indexes in a MongoDB Database as a Script

When you have collections with large amount of data, it is very important to create proper indexes. MongoDB queries can be substantially faster with proper indexes created on collections to meet the application needs of data sorting and filtering. MongoDB automatically creates a uniq index on the _id field during the creation of the collection. All other indexes must be manually created.

Sometimes programmers don’t maintain a separate script for all the indexes they create during the project. To resolve performance issues, they may create indexes directly on the database without adding them to a separate script file. This is a bad practice since when a similar database is created for testing purposes, it may be missing some important indexes causing all kinds of all application errors. In such situations, the following script will be handy to extract all indexes in a running MongoDb database.

The output of the following MongoDB script itself is a MongoDB script that can be executed on a different database instance to recreate all indexes. I will also recommend committing the output to your version control system and mandate developers to update it before applying an index on the database. You can also use the script to compare indexes on database in different environments such as dev, sit, uat and production.

How to Export All Indexes in a MongoDB Database as a script

// iterate through every collection in MongoDB database
db.getCollectionNames().forEach(function(collection) {
    var indexes = db.getCollection(collection).getIndexes();
    // now iterate through every index in the collection
    indexes.forEach(function(index) {
        // we don't need these as it will be auto created
        delete index.v;delete index.ns;
        var key = index.key;
        delete index.key
        var options = {};
        // let us also copy all options associated with the index
        // index property unique is an example
        for (var option in index) {
            options[option] = index[option]
        }
        // Create script output
        print("db.getCollection(\""+collection+"\").createIndex("+tojson(key)+", "+tojson(options)+");");
    });
});

You can run the above script as a file using MongoDB shell or you can simply copy paste and run the same on a MonogDB client such as RoboMongo. The output can be saved as a script file for creating indexes of the database.

Sometimes you may want to apply indexes on an existing collection to a copy of the collection on the same database. In such cases you can use the following script. You need to replace the collection names c1 and c2 with actual names of the collections in your database. Note the use of background option (only needed in MongoDB versions less than 4.2) to ensure that the index creation do not block operations on the collection.

How to Copy Indexes from One Collection to Another in MongoDB?

var indexes = db.c1.getIndexes();
// now iterate through every index in the collection
indexes.forEach(function(index) {
    // we don't need these as it will be auto created
    delete index.v;delete index.ns;
    var key = index.key;
    delete index.key
    var options = {};
    // let us also copy all options associated with the index
    // index property unique is an example
    for (var option in index) {
        options[option] = index[option]
    }
    // Copy indexes to a new collection!
    db.c2.createIndex(key, options);
});

Please note that all the examples given are tested on MongoDB 3.6. These scripts should also work if you are using MongoDB 3.6 API on an Azure CosmosDB database.

Comments are closed.