MongoDB删除索引

MongoDB删除索引

MongoDB 中我们要删除一个索引,可以使用 dropIndex 函数,在 dropIndex 函数里面指定要删除的索引名,即可删除指定的索引。

MongoDB删除索引详解

语法

db_name.table_name.dropIndex(indexName)

参数

名称 描述
db_name 数据库名
table_name 集合名
indexName 索引名

说明

直接在 dropIndex 函数里面指定要删除的索引名 indexName,即可删除指定的索引。

案例

我们首先,使用 mongo 命令,连接上数据库,具体命令如下:

mongo

如下图所示:

33_MongoDB删除索引.png

现在,我们使用 use 命令,切换到 haicoder 数据库,具体命令如下:

use haicoder

现在,我们使用 insert 插入四条记录,具体命令如下:

db.haicoder.insert([ {id:1, "url" : "haicoder.net/c", "score" : 100 }, {id:2, "url" : "haicoder.net/cpp", "score" : 90 }, {id:3, "url" : "haicoder.net/golang", "score" : 80 }, {id:4, "url" : "haicoder.net/java", "score" : 60 } ]);

执行完毕后,此时,如下图所示:

34_MongoDB删除索引.png

我们看到,此时提示我们成功插入了多条记录,现在,我们创建一个索引,具体命令如下:

db.haicoder.ensureIndex({url:1})

执行完毕后,此时,如下图所示:

35_MongoDB删除索引.png

现在,我们查看所有的索引,具体命令如下:

db.haicoder.getIndexes()

执行完毕后,此时,如下图所示:

36_MongoDB删除索引.png

我们看到,我们已经成功创建了索引,现在,我们删除该索引,具体命令如下:

db.haicoder.dropIndex("url_1")

执行完毕后,我们查看所有的索引,此时,如下图所示:

37_MongoDB删除索引.png

我们看到,我们已经成功删除了索引。

MongoDB删除索引总结

在 MongoDB 中我们要删除一个索引,可以使用 dropIndex 函数,在 dropIndex 函数里面指定要删除的索引名,即可删除指定的索引。