An effective GUI tool for managing and visualizing MongoDB data is MongoDB Compass. On the other hand, a well-liked Python web framework for creating web apps is called Flask. Integrating your MongoDB data into your Flask web application may benefit from connecting MongoDB Compass to Flask. Through your Flask web application, you can quickly read, write, and alter data saved in MongoDB thanks to this integration.
Required Modules
pip install pymongo
Connect MongoDB Compass to Flask
Import the PyMongo module
At first, we are importing the Flask into our code and we are creating a Flask app.
Python3
from flask import Flask from pymongo import MongoClient # Flask constructor takes the name of # current module (__name__) as argument. app = Flask(__name__) |
Connect Flask to MongoDB database
Here, we are connecting to a MongoDB server running on the local machine on the default port 27017.
Python3
|
Accessing Specific Database
We are accessing the specific MongoDB database.
Python3
db = client[ 'eshop-database' ] collection = db[ 'users' ] |
Retrieving Data from Specific Database
In this step, we are using a cursor that will return a cursor object that you can iterate over to access the individual documents.
Python3
documents = collection.find() |
Running the Flask App
In this step, we are creating a route that prints the data from MongoDB on running the Flask app and hitting the URL.
Python3
@app .route( '/' ) # ‘/’ URL is bound with hello_world() function. def hello_world(): documents = collection.find() for record in documents: print (record) return "HEllo" # main driver function if __name__ = = '__main__' : # run() method of Flask class runs the application # on the local development server. app.run() |
Complete Code:
Python3
# Importing flask module in the project is mandatory # An object of Flask class is our WSGI application. from flask import Flask from pymongo import MongoClient # Flask constructor takes the name of # current module (__name__) as argument. app = Flask(__name__) client = MongoClient( # The route() function of the Flask class is a decorator, # which tells the application which URL should call # the associated function. db = client[ 'eshop-database' ] collection = db[ 'users' ] @app .route( '/' ) # ‘/’ URL is bound with hello_world() function. def hello_world(): documents = collection.find() for record in documents: print (record) return "HEllo" # main driver function if __name__ = = '__main__' : # run() method of Flask class runs the application # on the local development server. app.run() |
Output: