Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Python MongoDB - create_index Query
Next article icon

InPyMongo,indexingis 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.


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.

Python
frompymongoimportMongoClient,ASCENDINGc=MongoClient("mongodb://localhost:27017/")db=c["indexDB"]col=db["users"]data=[{"name":"Alice","email":"alice@example.com"},{"name":"Bob","email":"bob@example.com"},{"name":"Charlie","email":"charlie@example.com"}]col.delete_many({})col.insert_many(data)print("Sample data inserted.")

Output

Sample data inserted
Output
Sample data

Explanation:

  • Connects to the local MongoDB server and selects theindexDBdatabase and users collection.
  • Clears existing documents in the collection usingdelete_many({}).
  • Inserts three sample user records into the collection usinginsert_many().

Examples

Example 1: Create index on a field

Python
frompymongoimportMongoClient,ASCENDINGc=MongoClient("mongodb://localhost:27017/")db=c["indexDB"]col=db["users"]idx_name=col.create_index([("name",ASCENDING)])print(idx_name)

Output

Output

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

Example 2: List all index

Python
frompymongoimportMongoClient,ASCENDINGc=MongoClient("mongodb://localhost:27017/")db=c["indexDB"]col=db["users"]foridxincol.list_indexes():print(idx)

Output

Output
Snapshot of the Output

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

Example 3: Drop an index

Python
frompymongoimportMongoClient,ASCENDINGc=MongoClient("mongodb://localhost:27017/")db=c["indexDB"]col=db["users"]col.drop_index("name_1")

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)

Python
frompymongoimportMongoClient,ASCENDINGc=MongoClient("mongodb://localhost:27017/")db=c["indexDB"]col=db["users"]res=col.create_index("index_created")print(res)

Output

index_created_1

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

Example 5: Create compound index

Python
frompymongoimportMongoClient,ASCENDINGc=MongoClient("mongodb://localhost:27017/")db=c["indexDB"]col=db["users"]res=col.create_index([("ascending_index",1),("second_descending_index",DESCENDING)])print(res)

Output

Output
Output

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

Related articles


https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp