萬盛學電腦網

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

Python 連接 MongoDB:pymongo 基礎操作 (CRUD、索引、聚合)

使用官方驅動 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']

CRUD 核心操作

Create (插入)

# 單筆
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")

Read (查詢)

# 單筆
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}})

Update (更新)

# 單筆更新
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
)

Delete (刪除)

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)

交易 (MongoDB 4.0+ 副本集)

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)。
  • ObjectId 自動生成,勿手動構造。
  • 大量寫入用 insert_many(..., ordered=False) 並行寫入。
  • 查詢投射 {'_id': 0} 減少網路傳輸。
  • 定期 db.command('collStats', 'collection') 監控儲存統計。
copyright © 萬盛學電腦網 all rights reserved