从Python到MongoDB的数据写入和连接?

2024-10-01 02:31:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从Python脚本连接到MongoDB,并直接将数据写入其中。希望DB填写如下:

John
Titles    Values
color     black
age       15

Laly
Titles    Values
color     pink
age       20

目前,它被写入一个.csv文件,如下所示,但希望像这样将其写入MongoDB:

^{pr2}$

使用Python连接MongoDB并直接向MongoDB写入字符串的正确方法是什么?在

提前谢谢,一定会投赞成票/接受答案


Tags: 文件csv数据脚本dbagemongodbjohn
1条回答
网友
1楼 · 发布于 2024-10-01 02:31:27
#Try this:
from pymongo import MongoClient

# connect to the MongoDB 
connection = MongoClient('mongodb://127.0.0.1:<port>')

# connect to test collection
db = connection.test

# create dictionary
student_record = {}

# save rec to dict
student_record = {'name': 'John Doe','grade': 'A+'}

#insert the record
db.test.insert(student_record)

# find all documents
results = db.test.find()

# display documents from collection
for record in results:
    out_name = str(record['name'])
    out_grade = str(record['grade'])
    print(out_name + ',' + out_grade)

# close the connection to MongoDB
connection.close()

相关问题 更多 >