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
相关推荐
冷雨夜中漫步5 小时前
Python快速入门(6)——for/if/while语句郝学胜-神的一滴6 小时前
深入解析Python字典的继承关系:从abc模块看设计之美百锦再6 小时前
Reactive编程入门:Project Reactor 深度指南喵手7 小时前
Python爬虫实战:旅游数据采集实战 - 携程&去哪儿酒店机票价格监控完整方案(附CSV导出 + SQLite持久化存储)!2501_944934737 小时前
高职大数据技术专业,CDA和Python认证优先考哪个?helloworldandy8 小时前
使用Pandas进行数据分析:从数据清洗到可视化肖永威9 小时前
macOS环境安装/卸载python实践笔记TechWJ9 小时前
PyPTO编程范式深度解读:让NPU开发像写Python一样简单枷锁—sha9 小时前
【SRC】SQL注入WAF 绕过应对策略(二)abluckyboy10 小时前
Java 实现求 n 的 n^n 次方的最后一位数字