2017-04-01 139 views
-1

我想从Python脚本连接到MongoDB并直接将数据写入它。希望DB来填充像这样: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的正确方法?

谢谢你在前进,并且一定会给予好评/接受的答案

回答

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