Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use MongoDB with Flask?

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.

like image 930
Zoid Avatar asked Jan 06 '17 21:01

Zoid


People also ask

Does Flask support NoSQL database?

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.

Which database is best for Flask?

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.

How do you connect a database to a Flask?

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).

Can we connect MongoDB with 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.


2 Answers

You can use any of these three libraries

  • Flask-PyMongo - https://flask-pymongo.readthedocs.io/en/latest/
  • Flask-MongoAlchemy - https://pythonhosted.org/Flask-MongoAlchemy/
  • Flask-MongoEngine - http://docs.mongoengine.org/projects/flask-mongoengine/en/latest/

I personally use flask mongoengine and every things work fine

like image 82
Mohammad Efazati Avatar answered Nov 07 '22 07:11

Mohammad Efazati


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.

like image 8
Muntaser Ahmed Avatar answered Nov 07 '22 06:11

Muntaser Ahmed