python将mongodb中的数据写入到postgresql中

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