萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

PyMongo 為 MongoDB 創建唯一索引:一行代碼搞定

MongoDB 索引是查詢性能的關鍵。使用 PyMongo 為集合字段創建唯一索引極其簡單,僅需一行代碼。本文給出最小化示例並補充常用索引選項。

基礎示例:為 user 集合的 user_name 創建唯一索引

import pymongo

# 連接(舊版 API,新版推薦 MongoClient)
mongo = pymongo.Connection('localhost')
collection = mongo['database']['user']

# 創建唯一索引
collection.ensure_index('user_name', unique=True)

現代 PyMongo 3+ 寫法

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)

常用索引選項速查

復合索引

# 複合唯一索引:user_id + date 唯一
collection.create_index([('user_id', 1), ('date', -1)], unique=True)

查看現有索引

for idx in collection.list_indexes():
    print(idx)

注意事項

  • 大集合創建索引會佔用大量內存/磁盤,生產環境務必加 background=True。
  • 唯一索引創建前若已有重複數據會報錯,需先清洗數據。
  • ensure_index 在 PyMongo 3.0+ 已棄用,統一用 create_index。

一行 create_index('field', unique=True),讓 MongoDB 幫你守住數據唯一性底線。

copyright © 萬盛學電腦網 all rights reserved
選項說明示例
unique=True唯一索引,插入重複值報錯create_index('email', unique=True)
background=True後台構建,不阻塞寫入create_index('created_at', background=True)
sparse=True稀疏索引,僅索引存在該字段的文檔create_index('optional_field', sparse=True)
expireAfterSeconds=NTTL 索引,自動過期刪除文檔create_index('created_at', expireAfterSeconds=3600)
collation指定排序規則(如大小寫不敏感)create_index('name', collation=Collation('en', strength=2))