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
相关推荐
副露のmagic22 分钟前
更弱智的算法学习 day34AllFiles27 分钟前
用Python turtle画出标准五星红旗,原来国旗绘制有这么多数学奥秘!亲爱的非洲野猪32 分钟前
Java线程池深度解析:从原理到最佳实践用户13779404999344 分钟前
基于遗传算法实现自动泊车+pygame可视化4***17541 小时前
强化学习中的蒙特卡洛方法pen-ai1 小时前
打通 Python 与 C++ 的参数传递机制至此流年莫相忘1 小时前
Python之深拷贝和浅拷贝像风一样自由20201 小时前
XGBoost、LightGBM、CatBoost 原理深度剖析与全面对比用户230826676651 小时前
Python的管道符(|)联合类型语法糖东木月1 小时前
使用python获取Windows产品标签