Syed Humza Shah


Engineering leader. Likes coffee. Loves to travel. Runs on a combination of optimism and pragmatism.

Read more about him here.

How to Store (Read/Write) Data in MongoDB with PyMongo

I was recently working on a prototype for a simple Flask storage app: data could be fed into the app and later read through an API. After using MongoDB for storage, I decided to write this up for people in a similar situation.

Python’s leading MongoDB driver is PyMongo and after using it, it becomes quite clear why.

The following code is using PyMongo to store data in MongoDB:

# python code

import pymongo

client = pymongo.MongoClient('mongodb://localhost:27017/')
doc = client['document_name']
coll = doc['collection_name']

def store_data():
    data_point['value_one'] = fetch_value_from_somewhere()
    data_point['value_two'] = fetch_value_from_somewhere_else()

The above code will store the data in a ‘collection’. For those coming from RDBMS, think of MongoDB’s collections as tables and its documents as the database. In the code above, a SQL analogy would be that the document_name database will have a collection_name table with the following columns: _id, value_one, and value_two. The value for _id column is added by insert_one by PyMongo, unless you specify one yourself.

The main difference from SQL however is that you don’t need to define the schema beforehand because structures are only put in place when data is being stored.

Reading data is equally simple:

# python code

def read_data(id):
    return collection.find_one({'_id': id})

With that, we can return a single matching document or None in case of no matches.