Hey everyone, in this post we will discuss about a very important topic. So welcome to thePython 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
Contents
- 1 Python Mongodb Connection – Getting Started With MongoDB
- 1.1 What Is NoSQL Database ?
- 1.2 What Is MongoDB ?
- 1.2.1 Features
- 1.3 Downloading And Installing MongoDB
- 1.3.1 Setting Environment Variable
- 1.4 Starting The MongoDB Server
- 2 Python Mongodb Connection – Basic CRUD Operations
- 2.1 PyMongo
- 2.1.1 Installing PyMongo
- 2.2 Creating A New Project
- 2.3 Establishing Connection With MongoDB Database
- 2.4 Create Operation
- 2.4.1 Creating Collection
- 2.4.2 Adding Data into Collection
- 2.4.3 Putting Documents Into Collection
- 2.4.3.1 Putting One Document at a Time
- 2.4.3.2 Putting Multiple Data at a Time
- 2.4.4 Let’s Get Code Together
- 2.5 Read Operation
- 2.6 Update Operation
- 2.6.1 Updating Single Document
- 2.6.2 Updating Multiple Documents
- 2.7 Delete Operation
- 2.7.1 Deleting One Document
- 2.7.2 Deleting Many Document
- 2.7.3 Deleting All Documents
- 2.1 PyMongo
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. Butthe 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 OnlySQL”.
- It is an alternative to traditionalrelational databases in which data is placed in tables and dataschemais 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.
- MongoDBstores 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 modelmaps to the objects in your application code, making data easy to work with.
- MongoDB isfree 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.
1 2 3 4 5 6 7 8 9 | [ { FirstName:"Raj", LastName:"Hamid", Age:20 }, { FirstName:"Harsh", LastName:"Kumar", Age:25 } ] |
Features
Some features of MongoDB is following –
MongoDB allows your teams to easily organize, use and enrich data – in real time, anywhere.
(Video) Python MongoDB Tutorial | MongoDB With Python | MongoDB Tutorial For Beginners | SimplilearnBest 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 MongoDBDownload.
- Now install it as usual you install any software. But if you are getting any issues then check thisInstall MongoDB.
- Now go to your command prompt and run the following command –
1 2 3 | "C:\Program Files\MongoDB\Server\4.0\bin\mongod.exe" |
Setting Environment Variable
Now you have to set your MongoDB path in Environment variable.
- So copy your path of MongoDB directory and paste it insystem environment variable area.

- 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
1 2 3 | mongod |
- you will see the following output.

- 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 mongodcommand in your command prompt and now you can see the MongoDB is not terminating.

- And inC:\data\db,you can see there is lots of files generated by MongoDB server.

Bingo, now your MongoDB server is running successfully.
Most important thing is that right now your MongoDB default port is 27017and 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.
1 2 3 | pip install pymongo |
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.

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.
1 2 3 4 5 6 | from pymongo importMongoClient connection = MongoClient('localhost', 27017) my_database = connection.restaurants_database |
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 oryou 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.
1 2 3 | my_database = connection['restaurants_database'] |
- 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 databaseinside 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.
1 2 3 | data = my_database.data |
Adding Data into Collection
Now you have to add some data into your collection. So write following code for adding data into collection.
1 2 3 4 5 6 7 8 | entry_data = { 'Name': 'Raj Restaurants', 'Location': 'Patna', 'Contact_No': 567899, 'Type' : 'Fast Food' } |
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.
1 2 3 4 5 | result = data.insert_one(entry_data) print("Data are successfully Inserted...") print('One post: {0}'.format(result.inserted_id)) |
On running you will get following output –

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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | entry_data1 = { 'Name': 'Kaveri Restaurants', 'Location': 'Ranchi', 'Contact_No': 356789, 'Type' : 'Veg Food' } entry_data2 = { 'Name': 'Basant Vihar', 'Location': 'Patna', 'Contact_No': 35635689, 'Type' : 'South Indian Food' } entry_data3 = { 'Name': 'Punjab Sweet House ', 'Location': 'Ranchi', 'Contact_No': 3567833489, 'Type' : 'Sweets' } data = data.insert_many([entry_data1, entry_data2, entry_data3]) print("Data are successfully Inserted...") print('Multiple posts: {0}'.format(data.inserted_ids)) |
- inserted_ids holds the id of the inserted document.
- Now run the above code, you will get following output.

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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | from pymongo importMongoClient # Establishing Connection with MongoDB server connection = MongoClient('localhost', 27017) # Creating Database my_database = connection.restaurants_database # Creating Collection data = my_database.data # Adding data into collection entry_data = { 'Name': 'Raj Restaurants', 'Location': 'Patna', 'Contact_No': 567899, 'Type' : 'Fast Food' } # Putting document into collection result = data.insert_one(entry_data) print("Data are successfully Inserted...") # Fetching inserted Id of document print('One post: {0}'.format(result.inserted_id)) |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | from pymongo importMongoClient connection = MongoClient('localhost', 27017) my_database = connection.restaurants_database data = my_database.data print("\n ---Reading One Document---\n") print(data.find_one({'Type': 'Sweets'})) print("\n ---Reading All Documents---\n") for rest_data in data.find(): print(rest_data) |
The output will be following –

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 isa 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | from pymongo import MongoClient connection = MongoClient('localhost', 27017) my_database = connection.restaurants_database data = my_database.data # Query for object defining which document to update update_query = { 'Name': 'Basant Vihar' } #Query for object defining the new values of the document updated_values = { '$set': { 'Name': 'Blue Moon' } } data.update_one(update_query, updated_values) print("\n ---UPDATED RECORDS--- \n") for x in data.find(): print(x) |
Let’s see the output –

- you can see Basant Vihar restaurants name updated to Blue Moon.
Updating Multiple Documents
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | from pymongo import MongoClient connection = MongoClient('localhost', 27017) my_database = connection.restaurants_database data = my_database.data # Update all the documents where the Location starts with "R" update_query = { "Location": { "$regex": "^R" } } updated_values = { "$set": { "Name": "Yellow Sapphire" } } x = data.update_many(update_query, updated_values) # Printing Number of updated documents print(x.modified_count, "documents updated.") print("\n ---UPDATED RECORDS--- \n") for x in data.find(): print(x) |
- 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 isquery object defining which document to delete. So let’s see it practically.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | from pymongo import MongoClient connection = MongoClient('localhost', 27017) my_database = connection.restaurants_database data = my_database.data # Query for deleting one document delete_query = { "Location": "Ranchi" } data.delete_one(delete_query) for x in data.find(): print(x) |
- 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | from pymongo import MongoClient connection = MongoClient('localhost', 27017) my_database = connection.restaurants_database data = my_database.data # Query for deleting many documents delete_query = { "Location": {"$regex": "^Patna"} } delete_docs = data.delete_many(delete_query) print(delete_docs.deleted_count, " documents deleted.") for x in data.find(): print(x) |
- 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | from pymongo import MongoClient connection = MongoClient('localhost', 27017) my_database = connection.restaurants_database data = my_database.data # Deleting all documents delete_docs = data.delete_many({}) print(delete_docs.deleted_count, " documents deleted.") for x in data.find(): print(x) |
CONGRATULATIONS , we have done all the CRUD operation very well.
So guys, it was all about thePython 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.
FAQs
How to connect with MongoDB with Python? ›
- Install Python Driver – PyMongo. PyMongo contains tools for working with MongoDB. ...
- Import MongoClient from pymongo. ...
- Create a connection to MongoDB Daemon Service using MongoClient. ...
- MongoClient is Ready. ...
- Close connection to MongoDB.
Creating a MongoDB database in Python
The first step to connect Python to Atlas is to create a cluster. You can follow the instructions from the documentation to learn how to create and set up your cluster. Next, create a file named pymongo_get_database.py in any folder to write PyMongo code.
Call the method server_info() of the client instance to check MongoDB server running Pymongo Python with the exception called ServerSelectionTimeoutError .
How to connect MongoDB with Python in PyCharm? ›Connecting through PyCharm Professional
I will click on the Database section. I will click on the + (plus) button, hover to Data Source and then click on MongoDB. Now, paste the connection string in the Host Section. We will be updating all the information like user, database name, password and the URL.
To create a connection between the MySQL database and Python, the connect() method of mysql. connector module is used. We pass the database details like HostName, username, and the password in the method call, and then the method returns the connection object.
How can I connect to the database in Python? ›- Install MySQL connector module. Use the pip command to install MySQL connector Python. ...
- Import MySQL connector module. ...
- Use the connect() method. ...
- Use the cursor() method. ...
- Use the execute() method. ...
- Extract result using fetchall() ...
- Close cursor and connection objects.
PyMongo, the official Python MongoDB driver library, is simple to use and offers comprehensive support for MongoDB databases. Python and MongoDB are an excellent combination for creating modern web apps, JSON APIs, data processors, and other applications.
How to save data in MongoDB using Python? ›Insert Into Collection
To insert a record, or document as it is called in MongoDB, into a collection, we use the insert_one() method. The first parameter of the insert_one() method is a dictionary containing the name(s) and value(s) of each field in the document you want to insert.
- Create database on MongoDB. Connect to MongoDB shell. Create "testdb" database. Create "user" collection and insert it to "testdb".
- User Settings. Connect to admin db. Create user administrator. ...
- Create connection to MongoDB on CPD. Set the required information.
The connect() constructor creates a connection to the MySQL server and returns a MySQLConnection object.
How do I know if MongoDB is connected? ›
- Start a terminal in the server that runs the federation server.
- Issue the following command: telnet < mongodb_server_name > 28017. If the connection is successful, you will receive the following similar output from the command. Trying 9.30. 252.5... Connected to 9.30. 252.5. Escape character is '^]'.
request def connect(host='http://google.com'): try: urllib. request. urlopen(host) #Python 3. x return True except: return False # test print( "connected" if connect() else "no internet!" )
How does Python integrate with PyCharm? ›- From the main menu, select File | New Projects Setup | Settings for New Projects (on Window and Linux) or File | New Projects Setup | Preferences for New Projects (on macOS).
- Select Python Interpreter settings.
To connect Python to Access: Add the path where you stored the Access file (after the syntax DBQ=). Don't forget to add the MS Access file extension at the end of the path ('accdb') Add the table name within the select statement.
Which Python module is used to connect to a database? ›SQLite is probably the most straightforward database to connect to with a Python application since you don't need to install any external Python SQL modules to do so. By default, your Python installation contains a Python SQL library named sqlite3 that you can use to interact with an SQLite database.
Which API do you use to connect to a database from Python? ›DB-API is Python's standard API used for accessing databases. It allows you to write a single program that works with multiple kinds of relational databases instead of writing a separate program for each one.
How does Python work with databases? ›Python being a high-level language provides support for various databases. We can connect and run queries for a particular database using Python and without writing raw queries in the terminal or shell of that particular database, we just need to have that database installed in our system.
Is Python necessary for MongoDB? ›Python needs a MongoDB driver to access the MongoDB database. In this tutorial we will use the MongoDB driver "PyMongo". We recommend that you use PIP to install "PyMongo". PIP is most likely already installed in your Python environment.
What IDE should I use for MongoDB? ›Studio 3T (formerly MongoChef)
Studio 3T is a power-packed cross-platform IDE (integrated development environment) especially designed for the MongoDB users. Owned by the 3T Software Labs, this MongoDB GUI tool lets you directly write SQL queries (similar to NoSQL Booster).
Java. Java is known as the “write once, run anywhere” language because of its support for multiple platforms. This allows using MongoDB with Java to be a natural fit.
How to insert bulk data in MongoDB using Python? ›
Bulk Insert
A batch of documents can be inserted by passing a list to the insert_many() method. PyMongo will automatically split the batch into smaller sub-batches based on the maximum message size accepted by MongoDB, supporting very large bulk insert operations.
MongoDB is a document-oriented database classified as NoSQL. It's become popular throughout the industry in recent years and integrates extremely well with Python. Unlike traditional SQL RDBMSs, MongoDB uses collections of documents instead of tables of rows to organize and store data.
How to update data in MongoDB using Python? ›You can update a record, or document as it is called in MongoDB, by using the update_one() method. The first parameter of the update_one() method is a query object defining which document to update. Note: If the query finds more than one record, only the first occurrence is updated.
How to manually connect to MongoDB? ›- MongoDB Documentation.
- Back to Start with Guides.
- Atlas.
- Sign Up for a MongoDB Account.
- Create a Cluster.
- Add a Database User.
- Configure a Network Connection.
- Load Sample Data.
- Paste a MongoDB connection string or URI.
- Import connection details automatically from other clients (e.g. Robo 3T)
- Import a URI file.
- Enter connection details manually.
const MongoClient = require('mongodb'). MongoClient; const assert = require('assert'); // Connection URL const url = 'mongodb://localhost:27017'; // Database Name const dbName = 'myproject'; // Create a new MongoClient const client = new MongoClient(url); // Use connect method to connect to the Server client.
What are the two types of connect? ›When there are two or more electrical devices present in a circuit with an energy source, there are a couple of basic means by which to connect them. They can be connected in series or connected in parallel.
How to install pip in Python? ›- Securely Download get-pip.py 1.
- Run python get-pip.py . 2 This will install or upgrade pip. Additionally, it will install setuptools and wheel if they're not installed already. Warning.
A quick and easy way to be able to run SQL queries with Python is using SQLite. SQLite is a library that utilizes an SQL database engine. It performs relatively fast and has been proven to be highly reliable. SQLite is the most commonly used database engine in the test environment.
Can I use MongoDB without Internet? ›This app is also useable offline, if one or more users disconnects from the network, they still have a fully-functional app experience that saves changes locally and will sync changes bi-directionally when the network is restored.
What is the default MongoDB connection string? ›
To connect to your local MongoDB, you set Hostname to localhost and Port to 27017 . These values are the default for all local MongoDB connections (unless you changed them).
How do I access MongoDB in my browser? ›By default, MongoDB starts at port 27017. But you can access it in a web browser not at that port, rather, at a port number 1000 more than the port at which MongoDB is started. So if you point your browser to http://localhost:28017, you can see MongoDB web interface.
How can I see my connectivity? ›Select the Start button, then type settings. Select Settings > Network & internet. The status of your network connection will appear at the top.
How do you check database connectivity? ›To test the connection to your database, run the telnet hostname port on your Looker server. For example, if you are running MySQL on the default port and your database name is mydb, the command would be telnet mydb 3306 . If the connection is working, you will see something similar to this: Trying 10.10.
What is the command to check connectivity? ›- Type “cmd” to bring up the Command Prompt.
- Open the Command Prompt.
- Type “ping” in the black box and hit the space bar.
- Type the IP address you'd like to ping (e.g., 192. XXX. X.X).
- Review the ping results displayed.
- Create database on MongoDB. Connect to MongoDB shell. Create "testdb" database. Create "user" collection and insert it to "testdb".
- User Settings. Connect to admin db. Create user administrator. ...
- Create connection to MongoDB on CPD. Set the required information.
In order to connect to MongoDB, python uses a library known as pymongo. You can add this library to your python environment, using the below command from the Anaconda environment. This library enables python to connect to MOngoDB using a db client. Once connected we select the db name to be used for various operations.
How to connect to MongoDB Atlas using Python? ›- Click Connect. ...
- Click Choose a connection method.
- Click Connect your application. ...
- Select Python and your version of the driver. ...
- Copy the provided connection string.
- Configure the provided connection string.
- the --packages option to download the MongoDB Spark Connector package. The following package is available: mongo-spark-connector_2. ...
- the --conf option to configure the MongoDB Spark Connnector. These settings configure the SparkConf object. Note.
connect (url, user, password) The connect method is used to establish a connection to a MongoDB objects. The method returns the reference to the database also. We can use the Mongo () instance and its getDB() method instead in some cases.
How to install MongoDB in Python? ›
...
To Install MongoDB Python on Windows, implement the following steps:
- Step 1: Download MongoDB.
- Step 2: Install MongoDB.
- Step 3: Verify MongoDB Installation.
- Step 4: Install MongoDB Python on Windows.
- Step 5: Verify MongoDB Python Connection.
SQLite. SQLite is probably the most straightforward database to connect to with a Python application since you don't need to install any external Python SQL modules to do so. By default, your Python installation contains a Python SQL library named sqlite3 that you can use to interact with an SQLite database.
How to create API in Python MongoDB? ›- Creating your local environment. NOTE: While working with Python, we would recommend to use virtual environment to keep all the project's dependencies isolated from other projects. ...
- Install dependencies. ...
- Start the MongoDB server. ...
- Collections in MongoDB. ...
- Create Users. ...
- Read Users. ...
- Update Users. ...
- Remove Users.
- Step 1: Creating a Collection Using PyMongo.
- Step 2: Inserting Data from JSON to MongoDB Python.
- Step 3: Filtering the Data.
- Step 4: Saving Data from MongoDB to JSON Python.
As most software applications need to interact with data in some form, programming languages like Python provide tools for storing and accessing these data sources. Using the techniques discussed in this tutorial, you'll be able to efficiently integrate a MySQL database with a Python application.
Is PySpark same as Python and Spark? ›PySpark has been released in order to support the collaboration of Apache Spark and Python, it actually is a Python API for Spark. In addition, PySpark, helps you interface with Resilient Distributed Datasets (RDDs) in Apache Spark and Python programming language.
Which is better Spark or PySpark? ›Spark is an awesome framework and the Scala and Python APIs are both great for most workflows. PySpark is more popular because Python is the most popular language in the data community. PySpark is a well supported, first class Spark API, and is a great choice for most organizations.
Is PySpark a Spark or Python? ›PySpark is the Python API for Apache Spark, an open source, distributed computing framework and set of libraries for real-time, large-scale data processing. If you're already familiar with Python and libraries such as Pandas, then PySpark is a good language to learn to create more scalable analyses and pipelines.