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 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:

# 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
# 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
   # should we continue?
   flag = input('Enter another record? ')
   if (flag[0].upper() == 'N'):
      flag = False

# find all documents
results = db.find()


# display documents from collection
for record in results:
# print out the document
print(record['name'] + ',',record['grade'])


# close the connection to MongoDB

If you have any questions please let me know.

Registration is Now Open for MongoDB University

Take free online courses from the creators of MongoDB. MongoDB University offers courses for both developers and DBAs.

  • Seven week courses give you flexibility to work through material when it suits your schedule.
  • Frequent assessments and check-ins by TAs and instructors help you verify your understanding.
  • A certificate of completion confirms your membership in our community of cutting-edge NoSQL technologists.

More than 100,000 people have enrolled in our courses to date.

Register now >

Podcast: Learning XPages with Mark Myers and Matt White

Based on his recent blog entry about learning XPages, we brought Mark Myers on the show to discuss his approach to wrapping your head around XPages, especially coming at it as a person with a strong Java background. Matt White was also on the podcast to offer the perspective of someone who has been helping people learn XPages for several years now. We discussed things like:

  • NOT thinking of XPages as “another Notes design element”
  • Coming to XPages from the Java developer perspective
  • The amount of learning resources and help available now versus a few years ago
  • Using Java and server-side JavaScript (SSJS)
  • Some of the struggles that newbies might face
  • And more…

Mark and Matt are both members of the London Developer Co-op, and they have graciously renewed the TakingNotes discount code for XPages101 online training courses. If you go to the website and sign up using the discount code “taking notes”, you will receive a 33% discount off the list price of your subscription.

Listen now >

Video: Scaling your website with Memcached

Hopefully by now you had a chance to listen to Mark Myers of the London Developer Co-Op talk about NoSQL and Memcached on Episode 142 of The Taking Notes podcast. As I learn more about NoSQL solutions including MongoDB and Memcached I want to share with you some of my favorite info tidbits.

In this video Robert Scoble interviews James Phillips, Co-Founder and Chief Strategy Officer of Northscale Technology providers of elastic data infrastructure software. They talk about Memecached and Membase. Membase is a product sold by Northscale.