MongoDB CRUD with flask

ELAKIA VM
featurepreneur
Published in
4 min readJul 31, 2022

What is MongoDB?

MongoDB is an open-source NoSQL database management program. NoSQL is used as an alternative to traditional relational databases. NoSQL databases are quite useful for working with large sets of distributed data. MongoDB is a tool that can manage document-oriented information, and store or retrieve information.

Why MongoDB?

While MongoDB is more flexible and ensures high and diverse data availability, a SQL Database operates with the ACID (Atomicity, Consistency, Isolation, and Durability) properties and provides more excellent reliability of transactions.

More than any other NoSQL database, and dramatically more than any relational database, MongoDB’s document-oriented data model makes it exceptionally easy to add or change fields, among other things. So if a developer needs to evolve an application quickly, MongoDB’s flexible data model facilitates this.

Setting up of MongoDB Account

Go to the MongoDB website login to google and create an account and set the password by creating a project then you will land on the page like this :

then you will have to go to the Network access and add your IP address.

Click Add current IP address button and give a comment for your IP address for example “my IP ”.

Starting with MongoDB CRUD

In python, we required PyMongo for working with MongoDB. So install pymongo

pip install pymongo

First, we have to import the required modules. We mainly use flask, pymongy & dotenv.

from crypt import methodsfrom flask import Flask, request, jsonifyimport pymongofrom pymongo import MongoClientfrom flask import Markupimport osfrom dotenv import load_dotenvapp = Flask(__name__)load_dotenv()MONGO_URI = os.environ.get('MONGO_URI')

In the above code, we are using the environment variable. For that, you have to create a file named .env and in that initialise the variable and set the value.

For the value, you have to copy it from the MongoDB account. In that, go to the home page from there click the button Connect then you will get something like this.

Here click Connect to application. Then you end on this page.

Copy that application code and change the password while you declare the values to the .env file.

Then connect the MongoDB client and declare the cluster name and the collection name

cluster = MongoClient('MONGO_URI')db      = cluster['hollywood']col     = db['movies']

First, We are getting the data in the JSON format for inserting one at a time. You can add n number of entries using API:

@app.route("/", methods=['POST'])def startpy():    name  = request.json['name']    genre = request.json['genre']    last_movie_id = get_last_movie_id()    current_movie_id = last_movie_id + 1    movie_dict = {         "movie_id": current_movie_id,         "name"    : name,         "genre"   : genre     }   col.insert_one(movie_dict)   return "success"

Now we have to increment the number of entries for that we will have a function:

def get_last_movie_id():     last_movie_id  = col.find().sort([('movie_id', -1)]).limit(1)     try:         last_movie_id = last_movie_id[0]['movie_id']     except:         last_movie_id = 0     return last_movie_id

Then for seeing all the entries :

def get_all_movie():    movie = col.find()    movie_list = []    for item in movie:    movie_dict = {         "movie_id": item['movie_id'],         "name"    : item['name'],         "genre"   : item['genre']     }     movie_list.append(movie_dict)     return jsonify(movie_list)

For getting particular entries:

@app.route("/get/<movie_id>", methods=['GET'])def get_one_movie(movie_id):    movie = col.find_one({'movie_id': int(movie_id)})    movie_dict = {         "name" : movie['name'],         "genre": movie['genre']     }    return movie_dict

For editing the existing entire:

@app.route("/edit/<movie_id>", methods=['POST'])def edit_movie(movie_id):    name  = request.json['name']    genre = request.json['genre']    movie_dict = {         "name" : name,         "genre": genre    }    col.update_many({'movie_id': int(movie_id)}, {'$set': movie_dict})    return 'success'

For deleting the entire:

@app.route("/delete/<movie_id>", methods=['DELETE'])def delete_one_movie(movie_id):    col.delete_many({'movie_id': int(movie_id)})    return 'success'

Then for testing, you can use Postman or Thunder Client and etc. Here we are going to use Thunder client it is in the VScode you can just install the extension.

First, you to run the code and go to Thunder client. Here go to POST request then insert in the JSON format.

Then for using the GET request see all the entries.

For seeing particular entries:

For editing entries:

For deleting entries :

Conclusion:

MongoDB is a database and it follows No SQL format. Then it is more flexible and ensures high and diverse data availability
I hope this article is useful.

Github link: https://github.com/elakiavm/mongoDB-python-crud

--

--