VOOZH about

URL: https://www.geeksforgeeks.org/python/indexing-in-mongodb-using-python/

⇱ Indexing in MongoDB using Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Indexing in MongoDB using Python

Last Updated : 15 Jul, 2025

In PyMongo, indexing is used to improve the performance of queries by allowing MongoDB to quickly locate and access the requested data without scanning every document in a collection. create_index() defines indexes to optimize queries and enforce constraints. MongoDB auto-indexes _id, but custom indexes can be added on fields using various directions and options.


👁 Image

Syntax

collection.create_index([(field, direction)], **options)

Parameters:

  • field: Field to index (e.g., "name")
  • direction: pymongo.ASCENDING or pymongo.DESCENDING
  • options: Additional index options like unique=True, name="customIndex" etc.

Here is our sample data.

Output

Sample data inserted
👁 Output
Sample data

Explanation:

  • Connects to the local MongoDB server and selects the indexDB database and users collection.
  • Clears existing documents in the collection using delete_many({}).
  • Inserts three sample user records into the collection using insert_many().

Examples

Example 1: Create index on a field

Output

👁 Output

Explanation: Creates an ascending index on the name field to speed up queries using name.

Example 2: List all index

Output

👁 Output
Snapshot of the Output

Explanation: Displays all indexes on the users collection. The default _id_ index and the created name_1 index will be shown.

Example 3: Drop an index

Output

Index dropped

Explanation: Drops the index named "name_1". You must pass the exact index name created earlier.

Example 4: Create index on a new field (default ascending)

Output

index_created_1

Explanation: Creates an ascending index (default) on a new field index_created.

Example 5: Create compound index

Output

👁 Output
Output

Explanation: ascending_index is indexed in ascending order, second_descending_index in descending order. This index improves performance for queries and sorts using both fields together.

Related articles

Comment
Article Tags: