時(shí)間:2024-02-14 10:20作者:下載吧人氣:26
前言
數(shù)據(jù)庫性能對軟件整體性能有著至關(guān)重要的影響,本文給大家分享了一次MongoDB數(shù)據(jù)庫查詢性能提高40倍的經(jīng)歷,感興趣的朋友們可以參考學(xué)習(xí)。
背景說明
1、數(shù)據(jù)庫:MongoDB
2、數(shù)據(jù)集:
3、業(yè)務(wù)場景:求平均數(shù)
進(jìn)化過程
在這里使用Python演示
最直接想到的方法
根據(jù)上面的業(yè)務(wù)場景描述,最容易想到的解決方法就是
from pymongo import MongoClient # 連接數(shù)據(jù)庫 db = MongoClient('mongodb://127.0.0.1:27017')['my_db'] # 簡化的查詢數(shù)據(jù)集A的條件 filter = {...} # 查詢Collection A a_cursor = db.a.find(_filter) a_docs = [x for x in a_cursor] # 變量的初始定義 count = 0 total = 0 # 加入需要用到的元素為第21個 index = 20 # 查詢Collection B,同時(shí)做累加 for a_doc in a _docs: b_doc = db.b.find_one({'uid':a_doc['uid'], 'date': a_doc['date']}) # 只有能查到相應(yīng)的結(jié)果時(shí),才可以 if b_doc is not None: total += b_doc['actions'][20]['number'] count += 1 # 求平均數(shù) if count > 0 : avg = total/count
網(wǎng)友評論