Python and MongoDB

Python and MongoDB are a fantastic match for building modern web applications, JSON APIs, data processors, and more. Read on for an overview of how to get started and deliver on the potential of this powerful combination.




Using MongoDB with Python

Python, the Swiss Army knife of today’s dynamically typed languages, is perhaps best known for its comprehensive library support and native support for common data manipulation and processing tasks. Python’s native dictionary and list data types make it second only to JavaScript for manipulating JSON documents – and arguably even more well-suited to working with BSON (MongoDB’s extended binary JSON format). PyMongo, the standard MongoDB driver library for Python, is easy to use and provides comprehensive support for interacting with MongoDB databases.

Objects retrieved from MongoDB through PyMongo are compatible with dictionaries and lists, so they're easily printable, iterable, and manipulable. Whether you're crunching numbers or spinning up JSON APIs, working with MongoDB Data is intuitive and productive.




How to Setup Python and MongoDB

You'll want to install the up-to-date Python for your system, install and update PyMongo, and either install MongoDB locally or set up a free MongoDB Atlas cloud account. If you do choose to use MongoDB Atlas, you'll find specific connection strings there to use to access your database from the command line and within your code.


To install PyMongo:

`python -m pip install pymongo`

To connect to MongoDB from Python:

from pymongo import MongoClient

client = MongoClient(‘<<MongoDB Connection String>>’)

If you’re connecting to a local MongoDB, you can omit the connection string entirely, or use ‘mongodb://localhost:27017/‘.

If you are using MongoDB Atlas, find the connection string on your Atlas console and insert it above (you will also need to make sure you’ve followed the Atlas instructions for white-listing your development IP address).

An example connection string for MongoDB Atlas is :

mongodb+srv://readonly:readonly@[demodata.rgl39.mongodb.net/demo?retryWrites=true&w=majority](http://demodata.rgl39.mongodb.net/demo?retryWrites=true&w=majority)

You can use this today to connect to a read-only demonstration cluster.




What You Need to Know

For the most part, working with MongoDB collections and documents in Python is a breeze. Unlike JavaScript, native Python dictionaries (prior to Python 3.6) didn’t have sorted keys, so pymongo's BSON classes provided a more JSON-like behavior for accessing data in MongoDB. If you’re moving data between PyMongo’s data structures and JSON, or accessing MongoDB documents by ids passed as strings, remember that you might need to convert back and forth between Python strings and ObjectIds as appropriate, for handling _ids, and some other BSON types.

For example, if you have an HTTP endpoint for retrieving a post by id, which would be a Python string:

from bson.objectid import ObjectId

def get(post_id):

post = client.db.posts.find_one({‘_id’: ObjectId(post_id)})


Working with MongoDB documents in Python is easy: just access them like dictionaries:

from bson.objectid import ObjectId

def get(post_id):

post = client.db.posts.find_one({‘_id’: ObjectId(post_id)})

title = post[‘title’]


PyMongo exposes an intuitive API for accessing databases, collections, and documents. Make sure to check out the PyMongo documentation for more detail on how to get started, and all of the functionality it exposes.

Also make sure that if you’re accessing a remote database, that you add exception handling code to your programs in case your connection goes down.




How to Use MongoDB With Python

When it comes to building applications with Python and MongoDB, you're in luck: there's a sophisticated framework with a strong following wherever you look. Django and Flask are world-class web development frameworks with which you can easily integrate PyMongo, Pandas provides spreadsheet-like tools for data science projects, and Google’s Tensorflow makes it possible to do advanced Machine Learning.

If you are into async Python we have you covered too, with the Motor library which extends PyMongo with async behavior.

If you’re starting a new project or looking for ways to streamline an existing application, Python and MongoDB are a great combination to work with. Give PyMongo a spin, and let us know what you build!



Ready to get started?

Try MongoDB in the cloud for free with MongoDB Atlas. No credit card required.