Docs Menu

Docs HomeDevelop ApplicationsPython DriversPyMongo

Optimize Queries with Indexes

On this page

  • Overview
  • Sample Application
  • Single Field Index
  • Compound Index
  • Multikey Index
  • Atlas Search Index
  • Create Search Index
  • List Search Indexes
  • Update Search Indexes
  • Delete Search Indexes
  • Text Index
  • Geospatial Index
  • Unique Index
  • Wildcard Index
  • Clustered Index
  • Remove an Index

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.

You can use the following sample application to test the code examples on this page. To use the sample application, perform the following steps:

  1. Ensure you have PyMongo installed.

  2. Copy the following code and paste it into a new .py file.

  3. Copy a code example from this page and paste it on the specified lines in the file.

1import pymongo
2from pymongo import MongoClient
3
4try:
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
17except Exception as e:
18 raise Exception(
19 "The following error occurred: ", e)
result = collection.create_index("<field name>")
print(f'Index created: {result}')

To learn more about single field indexes, see the Single-Field Indexes guide.

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.

result = collection.create_index("<array field name>")
print(f'Index created: {result}')

To learn more about multikey indexes, see the Multikey Indexes guide.

To learn more about Atlas search indexes, see the Atlas Search Indexes guide.

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.

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.

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.

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.

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.

result = collection.create_index([("<GeoJSON object field>", "2dsphere")])
print(f'Index created: {result}')

To learn more about geospatial indexes, see the Geospatial Indexes guide.

result = collection.create_index("<field name>", unique=True)
print(f"Index created: {result}")

To learn more about unique indexes, see the Unique Indexes guide.

result = collection.create_index({"$**": pymongo.ASCENDING})
print(f'Index created: {result}')

To learn more about wildcard indexes, see the Wildcard Indexes guide.

collection = database.create_collection("<collection name>", clusteredIndex={
"key": {"_id": 1},
"unique": True
})

To learn more about wildcard indexes, see the Clustered Indexes guide.

collection.drop_index("<index_name>")

To learn more about removing indexes, see Remove an Index in the Work with Indexes guide.

← Access Data From a Cursor