MongoDB as a Database in Python

Harsh Kumar Khatri
3 min readMar 25, 2020

In this article, we will be looking upon how we can use MongoDB as a database in python. So let’s start with the process.

First, we need to install MongoDB into our system. I will be telling you the process of installing it in Linux based os. For any other, you can google how to install it in your system.

For installation in Linux write the below commands in the terminal.

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 68818C72E52529D4 
sudo echo "deb http://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.0.list
sudo apt-get update
sudo apt-get install mongodb-org -y
sudo systemctl start mongod
sudo systemctl enable mongod

The above commands will get the things into the Linux repository. Then we will be seeing what all files are available for the update. Finally, we will be installing mongo-org which is the organizational version for MongoDB. Once it gets installed we will start it and enable it so that it reloads/starts as soon as our machine starts.

The installation process is completed. Now lets head to our python file. Open any of the editors and make a python file and install pymongo with pip.Once it is installed then you can import it in your file. Then you have to create your MongoClient.(for more refer to the image below)

Here the URL will be the host at which our mongodb is installed. For us it is localhost and the port will be 27017.

Now we will create a database. (Refer to the image below)

I have created a database with the name mydatabase. Now we will create a column that can be considered as a table but is not a table as the data is stored in JSON format. (Refer to the image below)

It will be created in the database we have created. Now seeing what all tables or databases we have. (Refer to the image below)

Running this file will give us default databases and notable ones. This is because if we do not have any data-set in the table the database and table are not created. So we have to enter some data into it which can be done with the command given below.

It will insert the data-set in our table and now if we run our file then we can see the database and the table which have been created.

For more commands which we can use in this, I am attaching the link of W3 schools below.

https://www.w3schools.com/python/python_mongodb_insert.asp

Originally published at https://harshblog.xyz on March 25, 2020.

--

--