Okay so I have Flask installed and I am wondering how I can connect and use a MongoDB database with a Flask app that I am starting to build soon.
Some of the prevalent databases that developers use with Flask-SQLAlchemy are SQLite, PostgreSQL, MySQL, etc. Flask also has plugins such as Flask-MongoEngine, Flask-MongoAlchemy, Flask-CouchDB, etc. to work with NoSQL document-based databases such as MongoDB, and CouchDB.
The most popular include MySQL, PostgreSQL and SQLite. This makes it easy to move data between our models and our database and it makes it really easy to do other things like switch database engines and migrate our schemas. There is a great Flask extension that makes using SQLAlchemy in Flask even easier.
In any directory where you feel comfortable create a folder and open the command line in the directory. Create a python virtual environment using the command below. Once the command is done running activate the virtual environment using the command below. Now, install Flask using pip(package installer for python).
PyMongo, the standard MongoDB driver library for Python, is easy to use and offers an intuitive API for accessing databases, collections, and documents. Objects retrieved from MongoDB through PyMongo are compatible with dictionaries and lists, so we can easily manipulate, iterate, and print them.
You can use any of these three libraries
I personally use flask mongoengine and every things work fine
I personally find the PyMongo library simple and easy to use.
You first need to import MongoClient
and create a connection:
from pymongo import MongoClient
client = MongoClient()
Then get your db instance and collection (table):
db = client.my_database
collection = db.my_collection
You can then manipulate your data by working with JSON documents that hold your data. There is a complete example on their website.
Take a look at this tutorial on how to use PyMongo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With