LAUNCHMongoDB 8.3 is built for the sub-100ms retrieval & zero downtime AI demands. Read blog >
AI DATAStop fighting your data layer. Get the memory & retrieval agents need to scale. Read blog >

How to Set Up Flask with MongoDB

Get Started Free
Learn more about Atlas

Flask is a widely adopted Python framework for building web applications. It allows Python developers to use their preferred language with all of its assets while building scalable and fast-to-start Python web applications. MongoDB Atlas is MongoDB’s Database-as-a-Service platform that allows developers the flexibility of working with complex data while developing faster than ever. The MongoDB Atlas platform is simple to set up and scale, making it the perfect database for web applications.

Integrating the Flask application with MongoDB creates a strong and scalable application stack. In this article, we will guide you through how to connect your Flask application to MongoDB Atlas.

PyMongo Support for Flask

PyMongo is the official MongoDB Driver for Python. Any Python application can consume the PyMongo driver by importing it and using the MongoClient instance. Flask applications can leverage PyMongo to access our MongoDB Atlas database.

Since Flask is all about improving the developer experience when developing web applications, the community created a widely adopted helper called Flask-PyMongo which is a wrapper around PyMongo, closely integrated with Flask. This article will use this framework to work with the free tier cluster available in MongoDB Atlas, allowing you to try this stack for free.

Getting Started with Flask-PyMongo

Mflix application is a known example movie browsing application on MongoDB University. The entire sample project is located in our mongodb-developer/flask-pymongo-example github repo.

You can clone this project and explore the README to set up your demo application or follow this article as we go over the essentials of this project.

In order to showcase a Flask application example integrated with Atlas, we will use the sample_mflix database in the MongoDB Atlas sample dataset. The facade of “mflix” application will use Flask-PyMongo library, exploring the basic Create, Read, Update, and Delete (CRUD) operations together with text search and aggregations.

This project uses a UI layer in a minified ReactJS front end and a Python Flask application to host the front end, and the back-end API to access the movies database.

Project Structure

The mflix directory holds the application logic. This includes:

The main directory holds the following files:

How to Install Flask with PyMongo

The project uses a standard pip installation requirements file that lists the latest version of the needed dependencies:

requirements.txt

Those will allow us to wire the Flask application instance with the PyMongo client using Flask-PyMongo Helper, as placed in the_ db.py_ file:

The above code initializes a global “db” object once using the MONGO_URI read from the .ini file:

We will replace the template sample_ini file with a relevant Atlas cluster connection string:

Getting Your Connection String

In order to create the client, you will need to pass the connection string to access your database.

The connection string can be found in the Atlas UI. The following steps will show you how to get your connection string:

1. Visit the Atlas I and ensure you are logged into your account.

2. Ensure you are on the Clusters page. It should be the default page but if not, select it from the left-hand menu on the page.

Go to your cluster page

3. Click the “Connect” button for the Cluster you created earlier.

Click the connect button.

4. Select “Connect your application.’”

5. Copy the provided connection string into the create code, substituting any values within <>, such as , with your details.

Starting the Application

Working with virtual environments in Python is a good practice, so for our example application, let’s create one named mflix_venv:

Install Dependencies:

Edit sample_ini to have your Atlas connection string:

Rename the sample_ini to .ini file:

Start the application:

This will output console messages about the server startup and its status. Your application should be available via a browser on http://localhost:5000.

How to Store Data Using PyMongo and Flask

All database access is routed through the global “db” object initialising the PyMongo client. The special variable object “g” is used here to define the PyMongo database in the global application context.

In MongoDB, information is stored in BSON Documents. BSON is a binary, JSON-like structure. It supports the same data types as JSON with a few extras such as date, raw binary, as well as more number types such as integer, long, and float.

A collection is what MongoDB calls a group of documents in one container. Let’s cover the basic Create, Read, Update, and Delete operations.

Create

The creation of documents can be done via the collection object and insert_one method. Let's look at the “add_comment” function:

The above function receives comment attributes and inserts one document into the comments collection.

Read

Reads in MongoDB can be done via a query using _find or find_one _which returns a cursor of documents or a single document respectively. Another option is to use aggregations to perform a more complex search or restructuring of data. For more information on aggregations, see this documentation.

Our application query can filter movies using both find and aggregate methods:

Find in get_movies

The find method is searching the movies collection and providing a query criteria and sort document based on user input. See this code in db.py file.

Aggregate in get_all_genres

The aggregation unwinds the genres array in each document and calculates a distinct list of possible genres.

Update

To update a document, a collection object can use the update_one method. In our example, we’re providing a filter and updated values for text and date of a comment:

Delete

To delete a document, a collection object can use the delete_one method. In our example, we’re providing an _id of a comment to delete it:

FAQs

Get started with Atlas today

Get started in seconds. Our free clusters come with 512 MB of storage so you can play around with sample data and get oriented with our platform.
Try FreeContact sales
GET STARTED WITH:
  • 125+ regions worldwide
  • Sample data sets
  • Always-on authentication
  • End-to-end encryption
  • Command line tools