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
相关推荐
dhxhsgrx2 小时前
PYTHON训练营DAY25伊织code4 小时前
PyTorch API 5 - 全分片数据并行、流水线并行、概率分布风逸hhh5 小时前
python打卡day25@浙大疏锦行魔尔助理顾问6 小时前
Flask如何读取配置信息jc_hook7 小时前
Python 接入DeepSeekchicpopoo7 小时前
Python打卡DAY25crazyme_68 小时前
深入掌握 Python 切片操作:解锁数据处理的高效密码Code_流苏9 小时前
《Python星球日记》 第69天:生成式模型(GPT 系列)于壮士hoho10 小时前
Python | Dashboard制作掘金-我是哪吒10 小时前
分布式微服务系统架构第131集:fastapi-python