在 MongoDB 中查看索引列表(getIndexes 使用指南)
详细介绍在 MongoDB 中查看集合索引的方法,包括使用 db.collection.getIndexes() 查询特定集合索引,以及编写脚本批量遍历当前数据库中所有集合的索引。
发布于
在 MongoDB 中管理与调优数据库性能时,了解集合上已有的索引至关重要。我们可以通过 MongoDB Shell 提供的 db.collection.getIndexes() 方法快速查看某个集合的索引详情,也可以编写脚本遍历整个数据库的所有集合。
查看指定集合的索引
要在指定集合上列出所有索引,可以使用 db.<collection>.getIndexes() 方法(将 <collection> 替换为您实际的集合名称):
db.posts.getIndexes();
该方法返回一个包含描述性文档的数组,每个文档对应一个索引的配置与元数据(包括索引版本、键结构、索引名称以及是否为隐藏索引等)。
输出示例:
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_"
},
{
"v" : 2,
"key" : {
"title" : 1
},
"name" : "title_1"
},
{
"v" : 2,
"key" : {
"tags" : 1
},
"name" : "tags_1"
}
]在上例中,posts 集合共有三个索引:
- 默认的主键索引
_id_; - 基于
title字段的正序索引title_1; - 基于
tags数组字段的多键(Multikey)索引tags_1。
查看当前数据库中所有集合的索引
如果想要一次性审查当前数据库内所有集合的索引配置,可以通过 JavaScript 脚本遍历集合名列表:
db.getCollectionNames().forEach(function(collection) {
var indexes = db.getCollection(collection).getIndexes();
print("Indexes on " + collection + ":");
printjson(indexes);
});
输出示例:
Indexes on articles:
[ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_" } ]
Indexes on employees:
[ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_" } ]
Indexes on posts:
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_"
},
{
"v" : 2,
"key" : {
"title" : 1
},
"name" : "title_1"
},
{
"v" : 2,
"key" : {
"tags" : 1
},
"name" : "tags_1"
}
]
Indexes on products:
[ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_" } ]该脚本遍历输出了 articles、employees、posts 和 products 四个集合各自的索引信息。
常用进阶技巧
[!TIP]
- 仅提取索引名称:若索引较多只需快速预览索引名,可以配合 JavaScript 的
map方法:db.posts.getIndexes().map(idx => idx.name); // 输出: [ "_id_", "title_1", "tags_1" ]- 查看索引占用空间:若想了解每个索引占用的磁盘/内存大小,可执行:
db.posts.totalIndexSize(); // 或查看集合详细统计: db.posts.stats().indexSizes;