嗨客网搜索

MongoDB查看索引

MongoDB查看索引

MongoDB 中我们要查看当前集合的所有的索引,我们可以使用 getIndexes 函数。getIndexes 函数会返回当前集合的所有的索引。

MongoDB查看索引详解

语法

db_name.table_name.getIndexes()

参数

名称 描述
db_name 数据库名
table_name 集合名

说明

使用 getIndexes 获取当前集合所有索引。

案例

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

mongo

如下图所示:

10_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 } ]);

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

11_MongoDB查看索引.png

我们看到,此时提示我们成功插入了多条记录,现在,我们查看当前的所有索引,具体命令如下:

db.haicoder.getIndexes()

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

12_MongoDB查看索引.png

我们看到,每个表默认都有一个 id 索引,现在,我们再次给 score 字段创建索引,具体命令如下:

db.haicoder.ensureIndex({score:1});

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

13_MongoDB查看索引.png

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

db.haicoder.getIndexes()

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

14_MongoDB查看索引.png

我们看到,此时,再次多了一个索引。

MongoDB查看索引总结

在 MongoDB 中我们要查看当前集合的所有的索引,我们可以使用 getIndexes 函数。getIndexes 函数会返回当前集合的所有的索引。

嗨客网顶部