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
相关推荐
Wellijohn5 小时前
我把公司内部的 12 个 CRUD 接口交给了 AI Agent,然后省出了两周2601_967980116 小时前
python pytest怎样测试代码伞伞悦读6 小时前
【第92期】逻辑回归的分数概率与阈值的实验与排查ch6237 小时前
🚀 从零构建本地文档智能审查 Agent:Vibe Coding 实战指南摇滚侠8 小时前
《On Java 中文版 基础卷》阅读笔记 接口 18Thanks_ks8 小时前
AI Agent 开发入门:用 Function Calling 让大模型学会 “动手干活”,附订单查询机器人实战专注仿真9 小时前
智能体训练之模仿学习:GAIL 算法详解与实战databook9 小时前
处理一批 PDF,怎么算真的处理完了承渊政道11 小时前
【Python编程快速上手—让繁琐工作自动化】(列表:把数据排成队,从下标取值到深拷贝)大胖爱学习_MJ12 小时前
Agent 如何安全地拿数据库密码?基于 HashiCorp Vault 的动态凭证下发