Reputation: 343
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.
Upvotes: 2
Views: 5749
Reputation: 28366
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.
Upvotes: 5