Checking if an Index exists in mongodb

Is there a command that i can use via javascript in mongo shell that can be used to check if the particular index exists in my mongodb. I am building a script file that would create indexes. I would like that if I run this file multiple number of times then the indexes that already exists are not recreated.

I can use db.collection.getIndexes() to get the collection of all the indexes in my db and then build a logic to ignore the ones that already exists but i was wondering if there is command to get an index and then ignore a script that creates the index. Something like:

If !exists(db.collection.exists("indexname")) 
{
    create  db.collectionName.CreateIndex("IndexName")
}

Solution 1:

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.

Solution 2:

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'}) 
}