MongoDB 索引是查詢性能的關鍵。使用 PyMongo 為集合字段創建唯一索引極其簡單,僅需一行代碼。本文給出最小化示例並補充常用索引選項。
import pymongo
# 連接(舊版 API,新版推薦 MongoClient)
mongo = pymongo.Connection('localhost')
collection = mongo['database']['user']
# 創建唯一索引
collection.ensure_index('user_name', unique=True)
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
db = client['database']
collection = db['user']
# create_index 是 ensure_index 的別名(推薦)
collection.create_index('user_name', unique=True)
| 選項 | 說明 | 示例 |
|---|---|---|
| unique=True | 唯一索引,插入重複值報錯 | create_index('email', unique=True) |
| background=True | 後台構建,不阻塞寫入 | create_index('created_at', background=True) |
| sparse=True | 稀疏索引,僅索引存在該字段的文檔 | create_index('optional_field', sparse=True) |
| expireAfterSeconds=N | TTL 索引,自動過期刪除文檔 | create_index('created_at', expireAfterSeconds=3600) |
| collation | 指定排序規則(如大小寫不敏感) | create_index('name', collation=Collation('en', strength=2)) |