软件下载吧文章资讯

分类分类

MongoDB数据库查询性能提高40倍的经历分享

2024-02-14 10:20作者:下载吧

前言

数据库性能对软件整体性能有着至关重要的影响,本文给大家分享了一次MongoDB数据库查询性能提高40倍的经历,感兴趣的朋友们可以参考学习。

背景说明

1、数据库:MongoDB

2、数据集:

3、业务场景:求平均数

进化过程

在这里使用Python演示

最直接想到的方法

根据上面的业务场景描述,最容易想到的解决方法就是

from pymongo import MongoClient
# 连接数据库
db = MongoClient('mongodb://127.0.0.1:27017')['my_db']

# 简化的查询数据集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,同时做累加
for a_doc in a _docs:
 b_doc = db.b.find_one({'uid':a_doc['uid'], 'date': a_doc['date']})
 # 只有能查到相应的结果时,才可以
 if b_doc is not None:
 total += b_doc['actions'][20]['number']
 count += 1

 # 求平均数
 if count > 0 :
 avg = total/count
展开全部

相关文章

说两句网友评论
    我要跟贴
    取消