首页 > 解决方案 > Mongodb Index Creation only if not already exists

问题描述

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.

标签: mongodbmongodb-query

解决方案


我不确定首先检查是否有好处,除非您打算缓存该响应。

当您调用 时db.collection.createIndex,它不会重新创建已经存在的索引,它会返回 ok:1."note" : "all indexes already exist"

db.collection.getIndexes这将采用与调用或listIndexes数据库命令相同的数据库锁。首先检查索引是否存在或只是尝试创建它没有太大区别。


推荐阅读