使用官方驅動 pymongo` 連接 MongoDB,涵蓋連線設定、CRUD 操作、索引管理、聚合管線、交易與連線池最佳實踐。
pip install pymongo
from pymongo import MongoClient
# 單機
client = MongoClient('mongodb://localhost:27017/')
# 副本集 (自動發現 Primary)
client = MongoClient('mongodb://host1:27017,host2:27017/?replicaSet=rs0')
# 連線池設定 (生產環境建議)
client = MongoClient(
'mongodb://localhost:27017/',
maxPoolSize=50,
minPoolSize=10,
serverSelectionTimeoutMS=5000
)
db = client['mydb']
collection = db['mycollection']
# 單筆
result = collection.insert_one({'name': 'Alice', 'age': 25, 'tags': ['python', 'dev']})
print(result.inserted_id)
# 批次
docs = [{'name': f'User{i}', 'age': 20+i} for i in range(100)]
result = collection.insert_many(docs)
print(f"Inserted {len(result.inserted_ids)} docs")
# 單筆
doc = collection.find_one({'name': 'Alice'})
print(doc)
# 多筆 (游標,懶惰載入)
cursor = collection.find({'age': {'$gte': 25}}).sort('age', -1).limit(10)
for doc in cursor:
print(doc)
# 投射 (只取需要欄位)
cursor = collection.find({}, {'name': 1, 'age': 1, '_id': 0})
# 計數
count = collection.count_documents({'age': {'$gte': 30}})
# 單筆更新
result = collection.update_one(
{'name': 'Alice'},
{'$set': {'age': 26}, '$inc': {'login_count': 1}}
)
print(f"Matched: {result.matched_count}, Modified: {result.modified_count}")
# 多筆更新
result = collection.update_many(
{'tags': 'python'},
{'$addToSet': {'tags': 'backend'}}
)
# Upsert (不存在則插入)
collection.update_one(
{'email': 'new@user.com'},
{'$setOnInsert': {'created_at': datetime.utcnow()}},
upsert=True
)
result = collection.delete_one({'name': 'Alice'})
result = collection.delete_many({'age': {'$lt': 18}})
# 單欄位唯一索引
collection.create_index('email', unique=True)
# 複合索引
collection.create_index([('age', 1), ('name', -1)])
# 文字索引 (全文搜尋)
collection.create_index([('content', 'text')])
# 查看索引
for idx in collection.list_indexes():
print(idx)
# 背景建立 (不阻塞寫入)
collection.create_index('field', background=True)
pipeline = [
{'$match': {'status': 'active'}},
{'$group': {'_id': '$category', 'count': {'$sum': 1}, 'avg_age': {'$avg': '$age'}}},
{'$sort': {'count': -1}},
{'$limit': 5}
]
for doc in collection.aggregate(pipeline):
print(doc)
with client.start_session() as session:
with session.start_transaction():
collection.insert_one({'x': 1}, session=session)
collection.update_one({'y': 2}, {'$inc': {'z': 1}}, session=session)
# 自動 commit,異常時 rollback
maxPoolSize) 避免頻繁建立連線。acknowledged (預設 True)。insert_many(..., ordered=False) 並行寫入。{'_id': 0} 減少網路傳輸。db.command('collStats', 'collection') 監控儲存統計。