问题描述
我是否可以通过mongo shell中的javascript使用一个命令,该命令可用于检查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.
我可以使用db.collection.getIndexes()获取数据库中所有索引的集合,然后构建一个逻辑来忽略已经存在的那些,但是我想知道是否有命令来获取索引,然后忽略创建索引的脚本.像这样:
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中创建索引是幂等操作.因此,运行db.names.createIndex({name: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.
createIndex()弃用的别名(从MongoDB 3.0开始)为 ensureIndex() ,这对于确实可以.
The deprecated (as of MongoDB 3.0) alias for createIndex() is ensureIndex() which is a bit clearer on what createIndex()
actually does.
修改:感谢ZitRo在注释中进行了澄清,如使用.
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:
- 从v3.0开始,我们可以使用
db.names.getIndexes()
,其中names
是集合的名称. 此处的文档. - 在v3.0之前,您可以访问
system.indexes
集合并按照下面所述进行操作find
- As of v3.0, we can use
db.names.getIndexes()
wherenames
is the name of the collection. Docs here. - Before v3.0, you can access the
system.indexes
collection and do afind
as bri describes below.
这篇关于检查mongodb中是否存在索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!