Connecting Python Application to MongoDB

Intro

Suryanarayanan
3 min readOct 9, 2023

Python is a general-purpose programming language used in various projects like data science, data engineering, web development, etc. MongoDB is a document-oriented general-purpose NoSQL database that can be used for multiple use cases. In this blog, we will learn how to connect a Python application and MongoDB Instance.

Ways to Connect:

To connect any application in any language to MongoDB, MongoDB offers us libraries in respective packages called drivers. Drivers are middleware that can be used to communicate between applications and the MongoDB database.

In Python, MongoDB offers us two drivers. They are

  • PyMongo — Used for synchronous applications
  • Motor — Used for Asynchronous Applications

In this blog, we will use PyMongo to connect to the database.

Prerequisites:

A MongoDB Instance — you can use a local MongoDB Instance or create a Free MongoDB Instance on the cloud.

Virtual Environment in Python(optional) — you can create one using the following command

python3 -m venv vitual_env_name

PyMongo — To install the PyMongo Driver, use the below command

pip3 install pymongo

Now, to the main part.

How To Connect the Application to the Database.

To Connect to a database, we need to follow a three-step process.

Step 0: Obtain database connection String.

Step 1: Import the client class from the library.

Step 2: Create an instance of the client class with the database connection string.

Let’s see each step in detail.

Step 0: Obtain database Connection String

For the local Database, your connection string will look like this

mongodb://username:password@localhost:<port> // port - > port which your mongodb instance uses. Usually it is 27017

For the databases in the cloud, we need to do the following.

  • Go to your atlas console.
  • Click Databases
  • Now, you can see the list of database clusters you have created. Click on the connect button in your desired database cluster.
  • Select Drivers in the list of options shown.
  • Under the section “Select your Driver and version” select Python as the driver and select the latest version. The latest version as of writing this article is 3.12.
  • Now In Section 3, you can see the connection string. copy or store it in a place to use in a few minutes.

Let’s dissect the connection string and understand it in more detail.

mongodb+srv://something:something@myatlasclusteredu.zynoxpv.mongodb.net/?retryWrites=true&w=majority

mongodb+srv — MongoDB Prefix

something:something — username and password to use to connect to the cluster.

“@somtext.text.text” — the domain of the cluster we have selected

Yes, we got the connection string but, we need to make some changes to the string. We need to change the password part because MongoDB atlas does not prefill the password in the connection string it is given.

So change the password to whatever password you have set for that user. IF needed, you change your username as well.

Let’s move to the next steps.

Step 1 & step 2:

First, let’s import the MongoClient from PyMongo.

from pymongo import MongoClient

create an instance of MongoClient with the connection string.

MONGODB_URI = 'your_connection_string'
client = MongoClient(MONGODB_URI)

Now It’s time to check our connection by pinging the database. Use the following line of code to ping.

print(client.admin.command('ping'))

If you have followed all the steps properly, then you should see an output similar to this in your console.

Ping Output

Troubleshooting

Following are some of the issues faced when you are trying to connect to MongoDB using drivers.

ServerSelectTimeOut — Check if you have added your IP address in the MongoDB network access tab.

Authentication Failed — Check your username and password and provide proper credentials.

Conclusion

That’s it for this post fellas. Thanks for reading till the end. If you find value in the blog post, give a clap or comment. 😃

For more content related to data engineering follow me on LinkedIn and Medium.

--

--