Python MongoDB Connection – An Introduction To MongoDB With Python

Hey everyone, in this post we will discuss about a very important topic. So welcome to the Python MongoDB Connection Tutorial. In this tutorial i will show you how  can you use MongoDB database using python and you will also learn what is MongoDB, why we use it, downloading and installing, basic CRUD operation and everything about it. So let’s gets started without any delay.

Python is very powerful language, you can develop different kinds of applications using python. In our previous tutorials, we have seen – how to work with SQL database using python, but in this post we will see how to work with NoSQL database using python. You can check some examples of SQL database from here.

Python MySQL Tutorial : Using MySQL Database with Python

CRUD Operation In Python PostgreSQL

Python Mongodb Connection – Getting Started With MongoDB

So in this section, we will learn what is MongoDB and why we use it. But before dealing with what is MongoDB, at first we have to understand what is NoSQL database because MongoDB is NoSQL database.

What Is NoSQL Database ?

For decades, SQL databases were the only option for developers looking to build large, scalable systems. But the ever-increasing need for the ability to store complex data structures led to the birth of NoSQL databases, which allow a developer to store heterogeneous and structure-less data.

  • NoSQL  stands for “Not Only SQL”.
  • It is an alternative to traditional relational databases in which data is placed in tables and data schema is carefully designed before the database is built.
  • NoSQL databases are especially useful for working with large sets of distributed data.

Now you can think which is good, so my answer is that neither SQL is bad nor NoSQL is bad. Both SQL and NoSQL have their strengths and weaknesses. So you have to select according to your application’s requirement. When choosing a database you should consider the strengths and weaknesses of each database carefully.

What Is MongoDB ?

Now let’s come to main focus of this topic that is MongoDB. So MongoDB is a NoSQL database.

  • MongoDB stores data in flexible, JSON-like documents, that means  fields can vary from document to document and data structure can be changed over time
  • The document model maps to the objects in your application code, making data easy to work with.
  • MongoDB is free to use.

This is a table of a SQL database.

First Name Last Name Age
Raj Hamid 20
Harsh Kumar 25

But in MongoDB, data are stored in JSON format. This is the structure of MongoDB document.

Features

Some features of MongoDB is following –

  • MongoDB allows your teams to easily organize, use and enrich data – in real time, anywhere.

  • Best way to work with data.

  • Put data where you need it.

  • Run anywhere.

Downloading And Installing MongoDB

Now you have to download and install MongoDB in your system. So follow the following steps –

  • Go to this URL and download MongoDB Download.
  • Now install it as usual you install any software. But if you are getting any issues then check this Install MongoDB.
  • Now go to your command prompt and run the following command –

Setting Environment Variable

Now you have to set your MongoDB path in Environment variable.

  • So copy your path of MongoDB directory and paste it in system environment variable area.
Python MongoDB Connection
Python MongoDB Connection

 

  • I am sure you already know how to go to the New System Variable, but anyway if you are getting any issue then check this link.

Starting The MongoDB Server

Now go to your command prompt and run following command

  • you will see the following output.
Python MongoDB Connection
Python MongoDB Connection
  • So you can see MongoDB is starting but shutting down. This is because of MongoDB is a document based database and it requires a db path where MongoDB can store files.
  • So in our case, right now we just started mongod without db path.
  • In the above image, i have marked the dbpath. So let’s create this path.
  • Open C drive and create a directory data and inside this data directory create a new directory db.
  • Now run again mongod command in your command prompt and now you can see the MongoDB is not terminating.
Python MongoDB Connection
Python MongoDB Connection
  • And in C:\data\db, you can see there is lots of files generated by MongoDB server.
Python MongoDB Connection
Python MongoDB Connection

Bingo, now your MongoDB server is running successfully.

Most important thing is that right now your MongoDB default port is 27017 and this port number should be remember because when you want to access your database from different applications, may be python or something else that time you need to provide this port number.

So now let’s start our main focus of this tutorial that is accessing MongoDB database using python.

Python Mongodb Connection – Basic CRUD Operations

Before performing CRUD operations, firstly you have to connect your database. So let’s see how to do that.

PyMongo

  • PyMongo is the official Python driver for MongoDB.
  • Why PyMongo – PyMongo was created to incorporate advantages of python as the programming language and MongoDB as database. Since python provides an easy to implement way of programming and MongoDB can easily handle the big data, the PyMongo tool can be of a great use since it provide best of utilities.

Installing PyMongo

  • You can install PyMongo module by running following command on your terminal.
  • Make sure you are connected to internet.

Creating A New Project

So now open your python IDE and create a new project and inside this project create a python file. Let’s see my project.

Python MongoDB Connection
Python MongoDB Connection

Establishing Connection With MongoDB Database

So to establishing connection with your database you need to do following tasks.

  • First you have to create a connection variable.
  • Then you have to create a database. There are two cases, either you are using an existing database or you want to create a new database
  • Now write the following code.

Explanation 

  • The first thing you have to do is importing MongoClient class. This is used to communicate with the running database instance.
  • Now you have to create a connection variable. And with pymongo call the MongoClient method. You have to pass two arguments to the MongoClient() method.
  • The first one is host name or IP address of MongoDB server where the MongoDB is installed and the second one is port number where your MongoDB is communicating to outside of server.
  • So our host name is localhost and port no. is 27017.
  • Now you have to create a database, so there is two cases either you are using an existing database or created a new database.
  • So for creating database, you have two options, either  you can create it as an attribute or you can also use the dictionary-style.
  • In the above code i have used as an attribute method but you can also use the dictionary-style. So the dictionary style method is following.

  • If you want to use an existing database then you have to simply put that database you want to connect.

When you run the above code, you will see your database is not created yet, this is because of that an empty database is not allowed inside MongoDB. So you need to actually create some collections inside your database to appear this database inside your MongoDB server .

Now we will perform CRUD(Create, Read, Update, Delete)operation in MongoDB database. So let’s gets started without any delay.

Create Operation

In create operation, you need to create a collection that means you have to insert some data into your database. So let’s see how to do that.

Creating Collection

In MongoDB terminology, a collection is a group of documents that are stored together within the database. So now to create a collection write the following code.

Adding Data into Collection

Now you have to add some data into your collection. So write following code for adding data into collection.

Putting Documents Into Collection

Now you have to put that document into your collection. Here you have two options, either you can put one document at a time or multiple document at a time.

Putting One Document at a Time

You can insert one document into your collection at a time by using insert_one() method. So write the following code.

On running you will get following output –

Python MongoDB Connection
Python MongoDB Connection
Putting Multiple Data at a Time

Now, if you have multiple documents then it will be a right choice to put them all together simultaneously. insert_many() method takes an array of document data. So for implementing this write the following code.

  • inserted_ids holds the id of the inserted document.
  • Now run the above code, you will get following output.
Python MongoDB Connection
Python MongoDB Connection

ObjectIds are dynamically generated when you insert data and consist of a Unix epoch, machine identifier, and other unique data. So don’t worry if you are not getting ObjectIds as mine.

Let’s Get Code Together

Read Operation

Now, in read operation we will fetch documents that are stored in our database. So write the following code.

  • To read one document, we will use find_one( ) method and to read each documents we will use iteration.

The output will be following –

Python MongoDB Connection
Python MongoDB Connection

Update Operation

In update operation, you can update your existing document with new values.

  • You have two options to update document. One is using update_one( ) method and second one is update_many( ) method.
  • To update records, you have to pass two parameters into update method.
  • One is a query object defining which document to update and second one is an object defining the new values of the document.

Updating Single Document

Let’s see it practically, so write the following code.

Let’s see the output – 

Python MongoDB Connection
Python MongoDB Connection
  • you can see Basant Vihar restaurants name updated to Blue Moon.

Updating Multiple Documents

  • In this example i have used regex , if you don’t know about regex then check this link.

Delete Operation

You can perform delete operation in MongoDB database in 3 ways. So let’s see all of them one by one.

Deleting One Document

So for deleting one document you have to use delete_one( ) method. It will take one parameter that is query object defining which document to delete. So let’s see it practically.

  • It will delete that document whose Location is Ranchi.
  • Remember one thing that if the query finds more than one document, only the first occurrence will be deleted.

Deleting Many Document

If you want to delete many document then you have to use delete_many( ) method. It will an argument that is a query object defining which documents to delete. So write the following code to do it.

  • It will delete all the documents which location is Patna.

Deleting All Documents

So for deleting all the documents, you have to call delete_many( ) method without any query object. That means you don’t need to pass any query object to delete_many method. So write the following code.

CONGRATULATIONS , we have done all the CRUD operation very well.

So guys, it was all about the Python MongoDB Connection tutorial. Yeah it is very lengthy but i am pretty sure you found it very helpful. If you did it, then share this article with your friends, that will surely helpful for me. And if you have any query regarding this then feel free to drop your comment in comment section.

Leave a Comment