• Python读取mongodb数据库


    先附上mongodb的数据存储结构

    然后直接附上完整代码:

    1. import pandas as pd
    2. import pymongo
    3. import time
    4. def get_time_stamp(str_time): # 字符串转时间戳, 获取13位时间戳
    5. time_array = time.strptime(str_time, "%Y-%m-%d %H:%M:%S")
    6. time_stamp = time.mktime(time_array) * 1000
    7. return int(time_stamp)
    8. def get_time_str(time_stamp): # 时间戳转字符串
    9. time_array = time.localtime(int(time_stamp) / 1000)
    10. time_str = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
    11. return time_str
    12. def get_data_by_tum(localID, begin_time, end_time, mongoaddress, mongobase):
    13. """
    14. # 从MongoDB中读取数据
    15. :param localID: list [deviceid,dataoffset,category],[56601,8,20]
    16. :param begin_time: 数据开始时间,'2023-03-10 15:14:13'
    17. :param end_time: 数据截止时间,'2023-04-20 15:14:13'
    18. :param mongoaddress: MongoDB address,'mongodb://username:password@host:port'
    19. :param mongobase: MongoDB name,'dbname'
    20. :return:
    21. """
    22. client = pymongo.MongoClient(mongoaddress) # 连接mongodb
    23. db = client.get_database(mongobase) # 获取db库
    24. collettions = db[str(localID[0])] # 获取collections中某个collection
    25. result = collettions.find(
    26. {'dataoffset': str(localID[2]),
    27. 'category': str(localID[1]),
    28. 'nowtime': {'$gte': begin_time, '$lte': end_time}}) # 获取该collection下面的数据
    29. timelist = []
    30. valuelist = []
    31. for r in result:
    32. timelist.append(get_time_str(r.get('nowtime'))) # 时间列表
    33. valuelist.append(float(r.get('value'))) # 数值列表
    34. result.close()
    35. if len(timelist) > 0:
    36. returndata = pd.DataFrame({'time': timelist, 'value': valuelist}) # 转换成数据框输出
    37. else:
    38. returndata = pd.DataFrame()
    39. return returndata
    40. if __name__ == '__main__':
    41. localID = [65826, 60, 1]
    42. mongo_full_address = "mongodb://username:password@host1:port1, host2:port2, host3:port3"
    43. mongobase = "dbname"
    44. begin_time = get_time_stamp('2023-07-10 15:14:13')
    45. end_time = get_time_stamp('2023-08-20 15:14:13')
    46. dataget = get_data_by_tum(localID, begin_time, end_time, mongo_full_address, mongobase)
    47. print(dataget)

  • 相关阅读:
    图解隐马尔可夫模型(HMM)
    Games104现代游戏引擎笔记 网络游戏进阶架构
    C++中常见的头文件
    华为云Stack首席架构师:打造“称手”的数字化工具,答好政企IT数字化转型这道必选题
    合宙Air724UG LuatOS-Air LVGL API控件-滑动条 (Slider)
    MySQL 路由配置以及部署方式
    C【整数正序分解】
    鸿蒙HarmonyOS实战-ArkUI组件(CustomDialog)
    nvm安装(非C盘安装)
    Web APIs 第03天上
  • 原文地址:https://blog.csdn.net/Trisyp/article/details/136377523