简体   繁体   中英

Python:How to insert array of data into mongodb using pymongo from a dataframe

Have a dataframe with values

df

name     rank  subject  marks  age  
tom      123    math     25     10
mark     124    math     50     10

How to insert the dataframe data into mongodb using pymongo like first two columns as a regular insert and another 3 as array

{
    "_id":  "507f1f77bcf86cd799439011",
    "name":"tom",
    "rank":"123"
    "scores": [{
        "subject": "math",
        "marks": 25,
        "age": 10
    }]
}

{
    "_id":  "507f1f77bcf86cd799439012",
    "name":"mark",
    "rank":"124"
    "scores": [{
        "subject": "math",
        "marks": 50,
        "age": 10
    }]
}

tried this:

convert_dict = df.to_dict("records")

mydb.school_data.insert_many(convert_dict)

I use this solution

convert_dict = df.to_dict(orient="records")

mydb.school_data.insert_many(convert_dict)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM