Python + MongoDB:如何从Python连接到MongoDB并写入数据?

时间:2017-04-01 00:15:33

标签: python mongodb

我想从Python脚本连接MongoDB并直接将数据写入其中。想要像这样填充数据库:

John
Titles    Values
color     black
age       15

Laly
Titles    Values
color     pink
age       20

目前,它被写入.csv文件,如下所示,但是想把它写成MongoDB:

import csv

students_file = open(‘./students_file.csv’, ‘w’)
file_writer = csv.writer(students_file)

…

file_writer.writerow([name_title]) #John
file_writer.writerow([‘Titles’, ’Values’])
file_writer.writerow([color_title, color_val]) #In first column: color, in second column: black
file_writer.writerow([age_title, age_val]) #In first column: age, in second column: 15

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

提前感谢您,并一定会upvote /接受答案

1 个答案:

答案 0 :(得分:0)

#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()