-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpython_mongo_simple_example.py
55 lines (43 loc) · 1.43 KB
/
python_mongo_simple_example.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# mongo_hello_world.py
# Author: Bruce Elgort
# Date: March 18, 2014
# Purpose: To demonstrate how to use Python to
# 1) Connect to a MongoDB document collection
# 2) Insert a document
# 3) Display all of the documents in a collection</code>
from pymongo import MongoClient
# connect to the MongoDB on MongoLab
# to learn more about MongoLab visit http://www.mongolab.com
# replace the "" in the line below with your MongoLab connection string
# you can also use a local MongoDB instance
connection = MongoClient("yourmongodbconnectionstring")
# connect to the students database and the ctec121 collection
db = connection.students.ctec121
# create a dictionary to hold student documents
# create dictionary
student_record = {}
# set flag variable
flag = True
# loop for data input
while (flag):
# ask for input
student_name,student_grade = input("Enter student name and grade: ").split(',')
# place values in dictionary
student_record = {'name':student_name,'grade':student_grade}
# insert the record
db.insert(student_record)
# should we continue?
flag = input('Enter another record? ')
if (flag[0].upper() == 'N'):
flag = False
# find all documents
results = db.find()
print()
print('+-+-+-+-+-+-+-+-+-+-+-+-+-+-')
# display documents from collection
for record in results:
# print out the document
print(record['name'] + ',',record['grade'])
print()
# close the connection to MongoDB
connection.close()