萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML 腳本教學

PyMongo 原子自增計數器:$inc 操作符實現高併發訪問統計

核心操作:$inc 原子增量

from pymongo import MongoClient
from bson.objectid import ObjectId

client = MongoClient('mongodb://localhost:27017/')
db = client['myblog']
articles = db['article']

article_id = "507f1f77bcf86cd799439011"  # 示例 ObjectId 字符串

# 原子自增 hit 字段,返回更新後文檔
result = articles.find_one_and_update(
    {'_id': ObjectId(article_id)},
    {'$inc': {'hit': 1}},
    return_document=True  # PyMongo 3.0+ 返回更新後文檔
)
print(f"New hit count: {result['hit']}")

關鍵優勢

  • 原子性:讀取-修改-寫入單操作完成,無競態條件
  • 高性能:無需應用層鎖,數據庫層面保證一致性
  • 就地更新:不需先查詢再保存,減少網絡往返

擴展:多字段同時自增

articles.update_one(
    {'_id': ObjectId(article_id)},
    {'$inc': {'hit': 1, 'daily_hit': 1, 'weekly_hit': 1}}
)

初始化確保字段存在

# 文檔創建時設置默認值
articles.insert_one({
    'title': 'Hello MongoDB',
    'hit': 0,
    'daily_hit': 0,
    'created_at': datetime.utcnow()
})

# 或用 $inc 配合 upsert(不存在則創建)
articles.update_one(
    {'_id': ObjectId(article_id)},
    {'$inc': {'hit': 1}, '$setOnInsert': {'hit': 0}},
    upsert=True
)

舊版本兼容 (PyMongo < 3.0)

# 僅更新,不返回新文檔
articles.update({'_id': ObjectId(article_id)}, {'$inc': {'hit': 1}})

# 需要新值時:先更新再查詢(非原子,有間隙)
articles.update({'_id': ObjectId(article_id)}, {'$inc': {'hit': 1}})
doc = articles.find_one({'_id': ObjectId(article_id)})
copyright © 萬盛學電腦網 all rights reserved