Optimize Queries with Indexes
On this page
Overview
On this page, you can see copyable code examples that show how to work with common types of indexes that you can use with PyMongo.
Tip
To learn more about working with indexes, see the Work with Indexes guide. To learn more about any of the indexes shown on this page, see the link provided in each section.
To use an example from this page, copy the code example into the
sample application or your own application.
Be sure to replace all placeholders in the code examples, such as <connection string URI>
, with
the relevant values for your MongoDB deployment.
Sample Application
You can use the following sample application to test the code examples on this page. To use the sample application, perform the following steps:
Ensure you have PyMongo installed.
Copy the following code and paste it into a new
.py
file.Copy a code example from this page and paste it on the specified lines in the file.
1 import pymongo 2 from pymongo import MongoClient 3 4 try: 5 uri = "<connection string URI>" 6 client = MongoClient(uri) 7 8 database = client["<database name>"] 9 collection = database["<collection name>"] 10 11 # start example code here 12 13 # end example code here 14 15 client.close() 16 17 except Exception as e: 18 raise Exception( 19 "The following error occurred: ", e)
Single Field Index
result = collection.create_index("<field name>") print(f'Index created: {result}')
To learn more about single field indexes, see the Single Field Indexes guide.
Compound Index
result = collection.create_index([ ("<field name one>", pymongo.ASCENDING), ("<field name two>", pymongo.ASCENDING) ]) print(f"Index created: {result}")
To learn more about compound indexes, see the Compound Indexes guide.
Multikey Index
result = collection.create_index("<array field name>") print(f'Index created: {result}')
To learn more about multikey indexes, see the Multikey Indexes guide.
Atlas Search Index
To learn more about Atlas search indexes, see the Atlas Search and Vector Search Indexes guide.
Create Search Index
index = { "definition": { "mappings": { "dynamic": True } }, "name": "<index name>", } collection.create_search_index(index)
To learn more about creating serach indexes, see the Create a Search Index guide.
List Search Indexes
results = list(collection.list_search_indexes()) print('Existing search indexes:\n') for index in results: print(index)
To learn more about listing search indexes, see the List Search Indexes guide.
Update Search Indexes
new_index = { "definition": { "mappings": { "dynamic": True } }, "name": "<index name>", } collection.update_search_index("<name of index to update>", new_index) print(f"Search index updated: {result}")
To learn more about updating search indexes, see the Update a Search Index guide.
Delete Search Indexes
collection.drop_index("<index name>") print(f"Search index deleted: {result}")
To learn more about deleting search indexes, see the Delete a Search Index guide.
Text Index
result = collection.create_index( [( "<field name>", "text")], default_language="english", weights={ "<field name>": 10 } ) print(f"Index created: {result}")
To learn more about text indexes, see the Text Indexes guide.
Geospatial Index
result = collection.create_index([("<GeoJSON object field>", "2dsphere")]) print(f'Index created: {result}')
To learn more about geospatial indexes, see the Geospatial Indexes guide.
Unique Index
result = collection.create_index("<field name>", unique=True) print(f"Index created: {result}")
To learn more about unique indexes, see the Unique Indexes guide.
Wildcard Index
result = collection.create_index({"$**": pymongo.ASCENDING}) print(f'Index created: {result}')
To learn more about wildcard indexes, see the Wildcard Indexes guide.
Clustered Index
collection = database.create_collection("<collection name>", clusteredIndex={ "key": {"_id": 1}, "unique": True })
To learn more about wildcard indexes, see the Clustered Indexes guide.
Remove an Index
collection.drop_index("<index_name>")
To learn more about removing indexes, see Remove an Index in the Work with Indexes guide.