python将mongodb中的数据写入到postgresql中

复制代码
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的索引作为一列写入到数据库中。
相关推荐
小小测试开发9 小时前
安装 Python 3.10+
开发语言·人工智能·python
梦想不只是梦与想10 小时前
Python 中的装饰器
python·装饰器
我叫唧唧波10 小时前
Python+AI 全栈学习笔记
人工智能·python·学习
copyer_xyf11 小时前
Python 异常处理
前端·后端·python
麻雀飞吧12 小时前
期货多合约策略目标持仓怎么更新才不乱
python·区块链
Cthy_hy12 小时前
拓扑排序超详解:原理 + Kahn 贪心算法
python·算法·贪心算法
LSssT.12 小时前
【01】Python 机器学习
开发语言·python
为爱停留12 小时前
给智能体装上「刹车」:中断(Interrupts)与人工审批全解析
python
l1t12 小时前
DeepSeek总结的使用实体-组件-系统和基于存在性处理进行Python编程39-40
开发语言·python
曾阿伦13 小时前
Python 搭建简易HTTP服务
开发语言·python·http