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
相关推荐
乾元4 分钟前
LLM 自动生成安全基线与等保合规初稿——把“网络工程事实”转译为“可审计的制度语言”全栈陈序员6 分钟前
【Python】基础语法入门(二十四)——文件与目录操作进阶:安全、高效地处理本地数据是有头发的程序猿9 分钟前
Python爬虫实战:面向对象编程构建高可维护的1688商品数据采集系统摸鱼仙人~12 分钟前
企业级 RAG 问答系统开发上线流程分析serve the people19 分钟前
tensorflow tf.nn.softmax 核心解析癫狂的兔子26 分钟前
【BUG】【Python】eval()报错啃火龙果的兔子27 分钟前
java语言基础masterqwer27 分钟前
day42打卡不会飞的鲨鱼29 分钟前
抖音验证码滑动轨迹原理(很难审核通过)我命由我1234529 分钟前
Python 开发问题:No Python interpreter configured for the project