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
相关推荐
喂完待续8 小时前
【Tech Arch】Spark为何成为大数据引擎之王王者鳜錸9 小时前
PYTHON让繁琐的工作自动化-猜数字游戏若天明10 小时前
深度学习-计算机视觉-微调 Fine-tune倔强青铜三10 小时前
苦练Python第39天:海象操作符 := 的入门、实战与避坑指南一百天成为python专家11 小时前
Python循环语句 从入门到精通Sunhen_Qiletian11 小时前
朝花夕拾(五)--------Python 中函数、库及接口的详解三年呀12 小时前
标题:移动端安全加固:发散创新,筑牢安全防线引言:随着移动互联网关山13 小时前
MCP实战悠哉悠哉愿意13 小时前
【Python语法基础学习笔记】if语句Q_Q196328847514 小时前
python的电影院座位管理可视化数据分析系统