Open In App

Get all the information of a Collection's indexes using PyMongo

Last Updated : 04 Jul, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

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

Python
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

Output
Single Field Index

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)

Python
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

Output
Compound Index

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

Python
from pymongo import MongoClient
c = MongoClient("mongodb://localhost:27017/")
db = c["mydb"]
col = db["users"]
col.drop()

col.insert_many([
    {"email": "[email protected]"},
    {"email": "[email protected]"},
    {"email": "[email protected]"}
])
col.create_index([("email", 1)], unique=True)
print(col.index_information())

Output

Output
Unique Index

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

Related articles


Next Article
Article Tags :
Practice Tags :

Similar Reads