![]() |
VOOZH | about |
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.
collection.create_index([(field, direction)], **options)
Parameters:
Here is our sample data.
Output
Sample data insertedExplanation:
Output
Explanation: Creates an ascending index on the name field to speed up queries using name.
Output
Explanation: Displays all indexes on the users collection. The default _id_ index and the created name_1 index will be shown.
Output
Index dropped
Explanation: Drops the index named "name_1". You must pass the exact index name created earlier.
Output
index_created_1
Explanation: Creates an ascending index (default) on a new field index_created.
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