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
相关推荐
花酒锄作田21 分钟前
Repository 模式在 FastAPI 中的应用2401_894915531 小时前
Geo 优化源码部署常见报错排查:连接失败、地图加载、地域词失效解决方案databook2 小时前
用递归消除法优化“特征子集”CAE二次开发工程师2 小时前
【C语言入门到精通】-基础篇森G3 小时前
comfyui安装ComfyUI-Manager失败问题-解决办法过期的秋刀鱼!3 小时前
倾斜数据集的错误指标-混淆矩阵能年玲奈喝榴莲牛奶4 小时前
使用AI编写-资产和漏洞管理系统DeepVisionary5 小时前
再观察小星火:当大厂分成“冰封“,国产轻模式创作者平台如何跑出加速度gb42152875 小时前
python中unstructured库和langchain-unstructured库在解析pdf文件的时候的区别?vx-程序开发5 小时前
django医院预约挂号系统---附源码23353