Connect MongoDB with Python ! CAN WE ??

Hello everyone! I am back with a new blog, I hope you all are great at your end. In this blog, we are going to explore what is MongoDB, how to connect MongoDB with python and we will create a database and a collection.

Quick Overview of MongoDB :-

MongoDB is a cross-platform, document oriented database that provides, high performance, high availability, and easy scalability.  MongoDB works on concept of collection and document.

  • In MongoDB no schema definition required.
  • It stores the data in form of key-value pair.
  • MongoDB is Document-based.

Difference between RDBMS(SQL) and MonoDB(NoSQL)


Connecting MongoDB with Python :-

To start with Python and MongoDB first of all we need to install a library known as pymongo. To install pymongo all you need is to open the Anaconda prompt and type the below command. pymongo is the library that helps us to connect Python with MongoDB.

Anaconda Prompt

Step 1: Open MongoDB Server

To start the MongoDB server, Open the command prompt and type mongod. The server will start on port number 27017 .

Step 2: Creating a Connection it with MongoDB server

Now, Import the pymongo to create the MongoDB Client. In MongoClient we pass the host and port number for the connection.


Step 3: Creating Database and Collection

In first we have created the database named Student using the variable client which we have created with the help of MongoClient. After creating the database we have created the collection named studentInfo.


We can see our created database and collection with the help of MongoDB Compass. But it will not show untill a single record has been inserted in the collection

Step 4: Storing Data in Collection

In this step we have created a variable named record that stored the data in the form of key pair value. After that we have stored that data in the collection with the help of insert_one method and pass the record as the parameter.


Insert multiple record in collection