MongoDB and Python: A Simple Example

The code below demonstrates how to use Python to connect to a MongoDB database. I chose to use a cloud based instance of MongoDB provided free of charge by MongoLab.com. The script demonstrates how to:

  • Use the PyMongo library to connect to a Mongo database
  • Insert documents into a collection
  • Display all of the documents from the collection

I also used a local instance of MongoDB for testing. You will will need to use a Python package manager such as EasyInstall to install the PyMongo library.

Here is the Python code:

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

If you have any questions please let me know.

Advertisement

Author: Bruce Elgort

You’ll find this technology professor – an award-winning instructor at Clark College – working hard to inspire and challenge his students with meaningful web development and programming experiences. With a skinny vanilla latte (no foam) in hand, Bruce loves to tinker and test the boundaries of existing and emerging technologies, to then guide hungry minds through memorable, educational journeys to showcase with passion the ever-evolving innovations of society. An industry leader, Bruce is known for co-developing Elguji’s IdeaJam software, and is recognized by IBM as an ‘IBM Champion’ for being an innovative thought leader in cloud technologies.

5 thoughts on “MongoDB and Python: A Simple Example”

  1. Thanks for this nice example. I’m currently using python to scrape then store data in text files. Using MongoDB instead of text files will be so much better.

  2. Thanks for that Bruce – I am just starting in this area with Python and MongoDb. As a test, I would like to use Python to pull in data from Weather underground into MongoDB, then possibly use D3 to create some nice visualisations. My focus now is on getting python to connect to WeatherUnderground (successful) but I am struggling with getting that data into MongoDB – any tips?

Comments are closed.

%d bloggers like this: