2017-04-01 58 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()