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
相关推荐
IVEN_11 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发Ray Liang13 小时前
用六边形架构与整洁架构对比是伪命题?AI攻城狮13 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践千寻girling13 小时前
一份不可多得的 《 Python 》语言教程AI攻城狮16 小时前
用 Playwright 实现博客一键发布到稀土掘金曲幽16 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析码路飞1 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议