Checking if an Index exists in mongodb

Mongodb

Mongodb Problem Overview


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

Mongodb Solutions


Solution 1 - Mongodb

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

Solution 3 - Mongodb

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;
  }
}

Solution 4 - Mongodb

maybe we can use something like https://docs.mongodb.com/v3.2/reference/method/db.collection.getIndexes/#db.collection.getIndexes to check if the collection have an index equal to something ?

if yes then drop and add the new one or add the new one directly

Solution 5 - Mongodb

In my case i did as follows.

   DBCollection yourcollectionName = mt.getCollection("your_collection");
    if (yourcollectionName.getIndexInfo() == null || yourcollectionName.getIndexInfo().isEmpty()) {         
      DBObject indexOptions = new BasicDBObject();
      indexOptions.put("pro1", 1);
      indexOptions.put("pro2", 1);       
      yourcollectionName.createIndex(indexOptions, "name_of_your_index", true);
     }

Solution 6 - Mongodb

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

    public async Task<bool> ExistIndex(string indexName)
    {
        var indexes = _collection.Indexes.List().ToList();

        var indexNames = indexes
            .SelectMany(index => index.Elements)
            .Where(element => element.Name == "name")
            .Select(name => name.Value.ToString());
        
        if (indexNames.Contains(indexName))
            return true;

        return false;
    }

PS. The _collection is my IMongoCollection from mongo.driver

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCSCView Question on Stackoverflow
Solution 1 - MongodbmetameView Answer on Stackoverflow
Solution 2 - MongodbbriView Answer on Stackoverflow
Solution 3 - MongodbDvir AradView Answer on Stackoverflow
Solution 4 - Mongodbctf0View Answer on Stackoverflow
Solution 5 - MongodbRamesh PapagantiView Answer on Stackoverflow
Solution 6 - MongodbSérgio BuenoView Answer on Stackoverflow