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
相关推荐
smj2302_796826522 小时前
解决leetcode第3989题网格中保持一致的最大列数吴梓穆3 小时前
Python 基础 正则表达式巧克力男孩dd3 小时前
Python超典型练习题(第一次作业)闲猫4 小时前
LangChain / Core components / Modelscui_ruicheng6 小时前
Python从入门到实战(十三):模块、包与环境管理李宸净7 小时前
Web自动化测试selenium+python而后笑面对7 小时前
生信bwa算法至乐活着8 小时前
深入Python内存管理与垃圾回收:从引用计数到分代回收的实战解析m0_547486668 小时前
《Python数据分析与挖掘》全套PPT课件㱘郳9 小时前
飞机大战Pygame存档