Get all the information of a Collection's indexes using PyMongo
In PyMongo, retrieving index information is useful for understanding how queries are optimized and what constraints are applied to a collection. The index_information() method provides metadata about all indexes in a collection, including index names, fields, sort order and options such as uniqueness. It helps verify custom indexes and optimize query performance beyond the default _id index.
Syntax
collection.index_information()
Parameters: This method doesn't take any parameters.
Returns: A dictionary where:
- Keys are the names of the indexes.
- Values are dictionaries describing each index.
Examples
Example 1: Single field index
from pymongo import MongoClient
c = MongoClient("mongodb://localhost:27017/")
db = c["mydb"]
col = db["users"]
col.drop()
col.insert_many([
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 30},
{"name": "Charlie", "age": 22}
])
col.create_index([("name", 1)])
print(col.index_information())
Output

Explanation:
- create_index([("name", 1)]) creates an ascending index on the name field.
- index_information() returns info about all indexes, including the default _id index.
Example 2: Compound Index (Multiple Fields)
from pymongo import MongoClient
c = MongoClient("mongodb://localhost:27017/")
db = c["mydb"]
col = db["users"]
col.drop()
col.insert_many([
{"name": "Alice", "city": "Delhi"},
{"name": "Bob", "city": "Mumbai"},
{"name": "Charlie", "city": "Bangalore"}
])
col.create_index([("name", 1), ("city", -1)])
print(col.index_information())
Output

Explanation:
- Compound indexes involve more than one field.
- ("name", 1), ("city", -1) indexes name in ascending and city in descending order.
Example 3: Unique index
from pymongo import MongoClient
c = MongoClient("mongodb://localhost:27017/")
db = c["mydb"]
col = db["users"]
col.drop()
col.insert_many([
{"email": "alice@example.com"},
{"email": "bob@example.com"},
{"email": "charlie@example.com"}
])
col.create_index([("email", 1)], unique=True)
print(col.index_information())
Output

Explanation: unique=True ensures that all values in the email field are distinct.
Related articles