Get a List of Indexes in MongoDB

In MongoDB, you can use the getIndexes() method to get a list of indexes on a collection.

You can also loop through each collection in a database to return all indexes in the database.

List Indexes for a Specific Collection

The db.collection.getIndexes() method returns the indexes on a given collection. Substitute the collection part for the actual name of the collection.

More specifically, this method returns an array that holds a list of documents that identify and describe the existing indexes on the collection, including hidden indexes.

Example:

db.posts.getIndexes()

Result:

[
	{
		"v" : 2,
		"key" : {
			"_id" : 1
		},
		"name" : "_id_"
	},
	{
		"v" : 2,
		"key" : {
			"title" : 1
		},
		"name" : "title_1"
	},
	{
		"v" : 2,
		"key" : {
			"tags" : 1
		},
		"name" : "tags_1"
	}
]

In this example, the posts collection has three indexes.

List All Indexes in the Current Database

We can take the previous example a step further and have it loop through all the collections in the current database, listing out all indexes for each collection.

Example code:

db.getCollectionNames().forEach(function(collection) {
    indexes = db.getCollection(collection).getIndexes();
    print("Indexes on " + collection + ":");
    printjson(indexes);
});

Example result:

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_" } ]

In this example, there are four collections: articles, employees, posts, and products, each with one or more indexes.