4

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 am thinking of using this, will it work:

if(db.collection.getIndexes().find({'name':'index_name'}).count()==0) { 
    db.collection.createIndex( { abc: 1, def: 1 } , { name: "index_name" } ) 
}

or, there is any better way to do this ? Also if above code is wrong, please help me with this task.

1 Answer 1

7

I'm not sure there is a benefit to checking first, unless you plan to cache that response.

When you call db.collection.createIndex, it will not re-create an index that already exists, it will return ok:1 with "note" : "all indexes already exist".

This will take the same database lock as calling db.collection.getIndexes or the listIndexes database command. There isn't much difference in checking to see if the index exists first, or just attempting to create it.

Sign up to request clarification or add additional context in comments.

4 Comments

Then please give me a solution for this task to be done.
Just run db.collection.createIndex and let the database determine whether to create it or not.
Does the above answer apply also to TTL indexes? What happens if the application calls CreateIndex for an already available TTL index, but sets a different ExpirationTime?
If the index already exists but has options different than the request, whether expiry or other option, it will return ok:0 with the message "already exists with different options"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.