mongodb 基于定义的数据模型使用PyMongo插入数据

ffscu2ro  于 2022-12-03  发布在  Go
关注(0)|答案(1)|浏览(162)

我有一个包含250行的数据集,如下所示:

在MongoDB Compass中,我插入了第一行,如下所示:

db.employees.insertOne([{"employee_id": 412153, 
                        "first_name": "Carrol", 
                        "last_name": "Dhin", 
                        "email": "carrol.dhin@company.com", 
                        "managing": [{"manager_id": 412153, "employee_id": 174543}], 
                        "department": [{"department_name": "Accounting", "department_budget": 500000}], 
                        "laptop": [{"serial_number": "CSS49745", 
                                    "manufacturer": "Lenovo", 
                                    "model": "X1 Gen 10", 
                                    "date_assigned": {$date: 01-15-2022}, 
                                    "installed_software": ["MS Office", "Adobe Acrobat", "Slack"]}]})

如果我想在Python中使用PyMongo将所有250行插入到数据库中,我如何确保每一行都遵循我在Mongo shell中手动插入时使用的格式?

wqsoz72f

wqsoz72f1#

from pymongo import MongoClient
import pandas as pd

client = MongoClient(‘localhost’, 27017)
db = client.MD
collection = db.gammaCorp

df = pd.read_csv(‘ ’) #insert CSV name here

data = {}

for i in df.index:
    data['employee_id'] = df['employee_id'][i]
    data['first_name'] = df['first_name'][i]
    data['last_name'] = df['last_name'][i]
    data['email'] = df['email'][i]
    data['managing'] = [{'manager_id': df['employee_id'][i]}, {'employee_id': df['managing'][i]}]
    data['department'] = [{'department_name': df['department'][i]}, {'department_budget': df['department_budget'][i]}]
    data['laptop'] = [{'serial_number': df['serial_number'][i]}, {'manufacturer': df['manufacturer'][i]}, {'model': df['model'][i]}, {'date_assigned': df['date_assigned'][i]}, {'installed_software': df['installed_software'][i]}]
    
    collection.insert_one(data)

相关问题