0

I would like to connect to MongoDB from a Python script and write data directly onto it. Would like the DB to be filled like so:

John
Titles    Values
color     black
age       15

Laly
Titles    Values
color     pink
age       20

Currently, it’s written to a .csv file like following, but would like to write it like so to 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

What would be the right approach to connecting to MongoDB using Python, and write strings directly to MongoDB?

Thank you in advance, and will be sure to upvote/accept answer

1 Answer 1

1
#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()
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.