Blog

List Indexes | MongoDB Indexing Tutorial

Key Takeaways

  • In mongosh, getIndexes() returns an array with one entry per index on a collection.
  • The underlying listIndexes command returns cursor metadata and batches; the Node.js driver exposes collection.listIndexes().
  • For a database-wide inventory, enumerate collections, exclude standard views, and handle failures separately for each collection.
  • Index definitions tell you what exists, not whether a query uses it. Inspect query plans with explain().

To list indexes in a MongoDB collection, run db.getCollection('documents').getIndexes() in mongosh. To inspect a database, enumerate its collections and call the helper on each one; application code should use its driver's index-listing API.

List Indexes in a MongoDB Collection

With your target database selected in mongosh, run:

db.getCollection('documents').getIndexes();

The getIndexes() shell helper returns index definitions for the documents collection, not the collection's documents. Each array entry describes one index.

Illustrative output for a collection with an _id index and an email/firstName compound index:

[
  {
    "v": 2,
    "key": { "_id": 1 },
    "name": "_id_"
  },
  {
    "v": 2,
    "key": { "email": 1, "firstName": 1 },
    "name": "email_1_firstName_1"
  }
]

The first definition is a single-field index on _id; the second is a compound index on email and firstName. The output depends on the indexes actually defined on your collection.

For a collection named people, the shorter shell syntax is:

db.people.getIndexes();

Read the Index Definition

  • v is the index version, not the MongoDB server version.
  • key identifies the indexed fields and their order. For ascending and descending indexes, 1 means ascending and -1 means descending.
  • name identifies the index. Unless you supply a custom name, MongoDB generates it from the field names and directions, so this compound index is named email_1_firstName_1, not email_1.

The three displayed fields aren't the complete possible result. Definitions can also include unique, sparse, expireAfterSeconds, partialFilterExpression, collation, or wildcardProjection, depending on the index. Compare options as well as keys when reviewing an inventory.

For creating these definitions, see creating MongoDB indexes; for uniqueness constraints, see MongoDB unique indexes.

Understand Compound Index Field Order

A compound index orders entries by its first field, then subsequent fields. The index { email: 1, firstName: 1 } supports queries on email and on email together with firstName; those combinations follow its leftmost prefix, meaning the fields at the beginning of the index. Don't assume it efficiently supports a query on firstName alone.

That distinction matters more than the index name. Read how MongoDB compound index prefixes work before deciding an existing index covers a query.

List Indexes for Collections Across a Database

A loop over getCollectionNames() is a useful starting point, but that method also returns view names. Standard views use their underlying collection's indexes and don't support listing regular indexes directly. Use getCollectionInfos() to filter by collection type instead.

db.getCollectionInfos(
  {
    type: { $in: ['collection', 'timeseries'] },
    name: { $not: /^system\./ }
  },
  { nameOnly: true }
).forEach(({ name }) => {
  try {
    const indexes = db.getCollection(name).getIndexes();
    print(`Indexes for ${name}:`);
    printjson(indexes);
  } catch (error) {
    print(`Could not list indexes for ${name}: ${error.message}`);
  }
});

This script includes ordinary and time-series collections, excludes standard views and system.* collections, and inspects only the current database. Each index-listing failure is reported without stopping the remaining collections.

Illustrative output for people and places, assuming these definitions exist:

Indexes for people:
[
  { "v": 2, "key": { "_id": 1 }, "name": "_id_" },
  {
    "v": 2,
    "key": { "email": 1, "firstName": 1 },
    "name": "email_1_firstName_1"
  }
]
Indexes for places:
[
  { "v": 2, "key": { "_id": 1 }, "name": "_id_" },
  { "v": 2, "key": { "location": 1 }, "name": "location_1" }
]

Treat this as a quick inventory, not an atomic snapshot: the script makes separate metadata requests. Keep its error messages with the output so a failed request isn't mistaken for a collection without indexes.

getIndexes() Versus the listIndexes Command

getIndexes() is a mongosh convenience helper around the listIndexes database command. You can issue the command directly:

db.runCommand({ listIndexes: 'documents' });

Unlike the helper's array, the command response contains a cursor document, including firstBatch and a cursor ID. If that ID is nonzero, retrieve subsequent batches with getMore; don't treat firstBatch as the complete inventory. Prefer the helper or a driver cursor unless you specifically need the command response.

List MongoDB Indexes with the Node.js Driver

The official Node.js driver provides collection.listIndexes(), which returns a cursor. Call toArray() to collect its index definitions.

In a Node.js project, install the driver:

npm install mongodb

Save the following as list-indexes.mjs. Set MONGODB_URI and MONGODB_DATABASE in your environment before running it; the .mjs extension enables ECMAScript module syntax.

import { MongoClient } from 'mongodb';

async function main() {
  const { MONGODB_URI, MONGODB_DATABASE } = process.env;
  if (!MONGODB_URI || !MONGODB_DATABASE) {
    throw new Error('Set MONGODB_URI and MONGODB_DATABASE.');
  }

  const client = new MongoClient(MONGODB_URI);
  try {
    await client.connect();
    const collection = client
      .db(MONGODB_DATABASE)
      .collection('documents');
    const indexes = await collection.listIndexes().toArray();
    console.dir(indexes, { depth: null });
  } finally {
    await client.close();
  }
}

main().catch((error) => {
  console.error(`Index listing failed: ${error.message}`);
  process.exitCode = 1;
});
node list-indexes.mjs

The script closes its client in finally and reports failures with a nonzero exit status. In a long-running application, reuse the application's MongoClient rather than creating and closing one for each request.

Troubleshoot Permissions

When access control is enabled, listing indexes requires the listIndexes privilege on the target collection. The built-in read role supplies that privilege for collections in its database. An authorization error doesn't mean the collection has no indexes.

The database-wide script also requires permission to enumerate collections through listCollections. Because enumeration happens before the loop, that failure won't be caught by its per-collection handler. For inventory-only tooling, request narrowly scoped metadata privileges rather than broader data access.

Check Index Performance Separately

Indexes can reduce the documents a query must examine. Without a usable index, a query may require a collection scan, but that isn't a rule for every operation. Indexes also consume storage and require maintenance during writes, so choose them around query patterns, selectivity—how narrowly a condition filters results—and your write workload.

Listing definitions doesn't establish that a query uses an index or benefits from it. Inspect a representative query:

db.getCollection('documents')
  .find({ email: 'reader@example.com' })
  .explain('executionStats');

Inspect the winning plan and compare totalKeysExamined, totalDocsExamined, and nReturned. An IXSCAN stage identifies an index scan; COLLSCAN identifies a collection scan. The executionStats mode executes the winning plan to completion, so use representative queries carefully on production data.

Continue with evaluating MongoDB index performance rather than adding indexes simply because an inventory looks short.

FAQ

How do I list indexes for a MongoDB collection?

In mongosh, run db.getCollection('documents').getIndexes(), replacing documents with your collection name. The result is an array containing one definition per index.

How do I list indexes for every collection in a database?

Enumerate collections with db.getCollectionInfos(), filter out standard views, and call getIndexes() for each collection. Handle errors separately and report excluded or inaccessible collections so the output isn't mistaken for a complete inventory.

What is the difference between getIndexes() and listIndexes?

getIndexes() is a mongosh helper that returns an array. The underlying listIndexes database command returns a response containing cursor metadata and batched index definitions.

Can I list MongoDB indexes from a driver?

Yes. With the official Node.js driver, await collection.listIndexes().toArray() to retrieve a collection's index definitions without using mongosh.

Why does a MongoDB index-listing command return an authorization error?

The authenticated user may lack the listIndexes privilege on the collection. A database-wide inventory also needs collection-enumeration privileges; the built-in read role supplies both for its database.

Further Reading

Written by Sam Erickson

Software engineer. I write every article on StackChief myself. Author of Mastering the Tech Interview. More about me