Checking if an Index exists in mongodb

Use db.system.indexes and search on it.

If, for example, you have an index called 'indexname', you can search for it like this:

db.system.indexes.find({'name':'indexname'});

If you need to search for that index on a specific collection,then you need to use the ns property (and, it would be helpful to have the db name).

db.system.indexes.find({'name':'indexname', 'ns':'dbname.collection'});

Or, if you absolutely hate including the db name...

db.system.indexes.find({'name':'indexname', 'ns': {$regex:'.collection$'}});

Pulling that together...

So, you're finished check would be:

if(db.system.indexes.find({name:'indexname',ns:{$regex:'.collection$'}}).count()==0) { 
    db.collection.createIndex({blah:1},{name:'indexname'}) 
}

I've created a custom method in c# to check if the index exists, using mongo driver:

public bool IndexExists<TDocument>(
    IMongoCollection<TDocument> collection, string name)
{
    var indexes = collection.Indexes.List().ToList();
    var indexNames = indexes
        .SelectMany(index => index.Elements)
        .Where(element => element.Name == "name")
        .Select(name => name.Value.ToString());
    
    return indexNames.Contains(name);
}

Using nodeJS MongoDB driver version 2.2:


const MongoClient = require('mongodb').MongoClient;

exports.dropOldIndexIfExist = dropOldIndexIfExist;
async function dropOldIndexIfExist() {
  try {
    const mongoConnection = MongoClient.connect('mongodb://localhost:27017/test');
    const indexName = 'name_1';
    const isIndexExist = await mongoConnection.indexExists(indexName);
    if (isIndexExist === true) {
      await mongoConnection.dropIndex(indexName);
    }
  } catch (err) {
    console.error('dropOldIndexIfExist', err.message);
    throw err;
  }
}

Creating indexes in MongoDB is an idempotent operation. So running db.names.createIndex({name:1}) would create the index only if it didn't already exist.

The deprecated (as of MongoDB 3.0) alias for createIndex() is ensureIndex() which is a bit clearer on what createIndex() actually does.


Edit: Thanks to ZitRo for clarifying in comments that calling createIndex() with the same name but different options than an existing index will throw an error MongoError: Index with name: **indexName** already exists with different options as explained in this question.


If you have other reasons for checking, then you can access current index data one of two ways:

  1. As of v3.0, we can use db.names.getIndexes() where names is the name of the collection. Docs here.
  2. Before v3.0, you can access the system.indexes collection and do a find as bri describes below.

Tags:

Mongodb