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中
最新推荐文章于 2025-07-17 09:43:18 发布