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.



  1. Jimmy Rustling says:

    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?

  3. Nice example for simple data insert operation. Found this one useful too

  4. Reblogged this on Pamungkas Jayuda.

  5. Muzaffar says:

    Simple and clear example

%d bloggers like this: