A few days back I've published an article about MongoDB explaining its use cases and how it is solving the industry problems efficiently. Now it's time to do some practical, in this article I'm gonna use CURD operations in the MongoDB cluster using the Python Flask application.
First let's create MongoDB Cluster:-
To create the cluster go to the MongoDB website. Sign up with Email and set up your account.:-
Choose the Free tier to use free services:-
Select the Cloud service provider and availability zone:-
Now the cluster is created, go to the collections to create the new database:-
Click on Add my own data :-
Give the database name and collections name and click on create :-
Now the database is created, go to the overview and on the right-centre corner click on connect :-
First, you have to configure the firewall you can either set your own IP or you can set 0.0.0.0/0 so that any computer can connect to the cluster:-
Now create the user and password :-
Now at the bottom click Choose a connection method :-
Click on the button Connect your application :-
It will give you a connection string copy this connection string to your python code, don't forget to replace the database name , username and password .
My connection string looks like this:-
mongodb+srv://admin:ab12345678cd@cluster0.gx5mz.mongodb.net/mydb?retryWrites=true&w=majority
Now its time for the Flask App:-
So I've created three files:-
- index.html (Main HTML file where I've created all the inputs)
- app.py (Python file where I've written the flask app code)
- res.html (HTML file with the jinja templating where all the responses are shown)
Index.html:-
App.py:-
Res.html:-
So these are the files, now its time to run the code:-
flask run
It will run the application, and by default, it runs on http://127.0.0.1/5000 .
Now if you insert something in the fields and click on the Submit Query button:-
Even if you check the database:-
If you found a error like this :- Just change your connection string from:-
mongodb+srv://admin:<password>@cluster0.gx5mz.mongodb.net/<database_name>?retryWrites=true&w=majority
To this :-
mongodb+srv://admin:<password>@cluster0.gx5mz.mongodb.net/<database_name>?ssl=true&ssl_cert_reqs=CERT_NONE
So now our task is complete of connecting Flask application with MongoDB cluster.