from pymongo import MongoClient
import pandas as pd
from sqlalchemy import create_engine
# 连接到MongoDB
mongo_client = MongoClient('mongodb://localhost:27017/')
db = mongo_client['test']
collection = db['aggtest']
# 查询数据
cursor = collection.find({}) # 这里使用空查询来获取所有文档
data = list(cursor)
# 将数据转换为Pandas DataFrame
df = pd.DataFrame(data)
# 连接到PostgreSQL(使用SQLAlchemy作为ORM)
engine = create_engine('postgresql://postgres:foxconn.88@localhost:5432/test')
# 将DataFrame写入到PostgreSQL(如果表不存在,会自动创建)
table_name = 'tabletest'
df2=df.drop(columns="_id")
print(df)
df2.to_sql(table_name, engine, if_exists='fail',schema="schtest", index=False)
# 注意:if_exists='append' 表示如果表已存在,则追加数据;如果表不存在,则创建表。
# index=False 表示不将DataFrame的索引作为一列写入到数据库中。
python将mongodb中的数据写入到postgresql中
半吊子的程序狗2024-10-29 9:10
相关推荐
林炳然1 分钟前
Python-Basic Day-1 基本元素(数字、字符串)weixin_307779134 分钟前
在Linux服务器上使用Jenkins和Poetry实现Python项目自动化今天没有盐5 分钟前
内置基础类型之布尔值类型(bool)与时间与日期类型Empty_7778 分钟前
Python编程之常用模块Q_Q51100828533 分钟前
python+uniapp基于微信小程序的学院设备报修系统蓝色空白的博客1 小时前
自动化测试脚本-->集成测试部署思路整理(1)Blossom.1181 小时前
把AI“绣”进丝绸:生成式刺绣神经网络让古装自带摄像头星星也在雾里1 小时前
【管理多版本Python环境】Anaconda安装及使用用户3721574261352 小时前
使用 Python 将 CSV 文件转换为 PDF 的实践指南大佬,救命!!!2 小时前
算法实现迭代2_堆排序