Many Python developers choose MongoDB for its speed, flexibility, and scalability. This NoSQL database adapts to different types of data, letting you build features regardless of data structure complexity. It’s a natural choice for applications that have to store lots of different information, handle constant changes, or manage large volumes of data.
From this tutorial, you’ll learn how to connect MongoDB using Python Connector from Devart to create, read, update, and delete data. Keep reading for detailed guidance!
Table of contents
- Technology background and preparation
- Connectivity architecture
- How to install Devart Python Connector for MongoDB
- How to create a user in the MongoDB database
- How to connect a Python application
- How to create a connection and query data from MongoDB
- Conclusion
Technology background and preparation
For this tutorial, we will use the Python Connector for MongoDB from Devart, which will provide you with an easy way to connect to a MongoDB database from your Python application through TCP/IP, using the libmongoc client library.
Also, for demonstrational purposes, we’ll use the Anaconda open-source platform to develop and deploy secure Python solutions. Note that you can choose any other IDE you’re familiar with (e.g., PyCharm, Jupyter, etc.) to develop Python applications, the flow will be the same, so you can still use this tutorial as a reference to learn how to connect your preferred development tool with a MongoDB database.
Another important detail is that we’re going to use the Python Connector for MongoDB from Devart, which will provide you with an easy way to connect to a MongoDB database from your Python application through TCP/IP, using the libmongoc client library.
If you haven’t installed all the needed tools and drivers yet, make sure to do it before you proceed further. For this tutorial, you’ll need to install the MongoDB Community edition, and get the Devart Python Connector for MongoDB.
Depending on the Python version on your machine, you’ll also have to download the Python Connector version that supports it. If you’re using Windows, to check the Python version, run the command in the Command Prompt:
python --version
In the output, you’ll see what Python version is installed. Now you’ll be able to download the specific Python Connector for MongoDB that will work for you.
Connectivity architecture
As we proceed to the process of setting up the connection to MongoDB using Python Connector, let’s explore the architecture in detail. In the image below, you can see an illustration of how this connection is supposed to work.
In our case, we’ll have a Python application built on the Anaconda platform, which uses Devart Python Connector for MongoDB driver as a middle layer to connect with MongoDB database, that is hosted in the Cloud, or on-prem.
After we set up the connection, we’ll perform CREATE, UPDATE, and DELETE operations on data stored in the MongoDB database. These are the common operations that are often used to modify data.
Now that the task at hand is clear, let’s move on to the practical section of this guide.
How to install Devart Python Connector for MongoDB
First off, let’s start with installing Devart Python Connector for MongoDB.
The easiest way to install Devart Python Connector for MongoDB is to get it from the Python Package Index.
To do this, if you’re using Anaconda, follow the steps described below.
- Let’s open Anaconda Prompt in the Navigator.
- Enter the command line to check the pip library.
py -m pip --version
If pip library is not installed, you can run the command to do it.
python -m ensurepip --upgrade
- Install Devart Python Connector for MongoDB using pip:
python -m ensurepip --upgrade
You can also install Devart Python Connector for MongoDB from the archive file that you have previously downloaded.
First, unzip the archive file that you have previously downloaded.
In the unzipped folder, there are two .whl files for Windows 32-bit and 64-bit. You have to install the package that matches your architecture.
Ensure you have pip library installed as described above. Then follow these steps:
- Run the command to install Python Connector for MongoDB. Don’t forget to replace <Path to unzipped folder> with an actual path to the connector.
pip install <Path to unzipped folder>/
devart_mongodb_connector-1.1.0-cp312-cp312-win_amd64.whl
If you encounter the error message, similar to the one shown below, run the command “pip debug -verbose.”
- Now, go to Compatible Tags and check if the tag cp312-cp312-win_amd64 is supported. In the list of compatible tags, pip only supports versions till cp311-cp311-win_amd64.
- Let’s rename the file devart_mongodb_connector-1.1.0-cp312-cp312-win_amd64.whl to devart_mongodb_connector-1.1.0-cp311-cp311-win_amd64.whl in the zipped folder. To do it, run the command with the new file name.
pip install
C:\Working\11-Tech-Published-Articles\29-Devart-Python-Connector-MongoDB\Sources\DevartPythonMongoDB\whl\devart_mongodb_connector-1.1.0-cp311-cp311-win_amd64.whl
After that, the message about the successful installation will appear.
Now, you are ready to build a Python application that’s going to be connected to MongoDB.
How to create a user in the MongoDB database
Most likely, you already have installed the MongoDB database to your system.
Now, for demonstrational purposes, we are going to show how to create a demo mongodb database (we’ll name it “Netflix”) and a database user with the owner rights to operate this database.
Note that if you already have a database, you might want to skip this step. Alternatively, you might want to follow this guide to test the waters.
- Use mongosh to connect to MongoDB.
mongosh --port 27017
As a result you should see the output like in the screenshot below.
- Use the “use Netflix” command to create a database. Alternatively, you can use a different database name that suits your project.
- Switch to the admin database mode and create a new user with the following commands.
use admin
db.createUser(
{
user: "netflix", pwd: "netflix#123", cleartext password roles: [ { role: "dbOwner", db: "Netflix" } ]
}
)
Now, you have created a new database user, and you’ve got one MongoDB database with empty collections.
How to connect a Python application
Now, it’s time to connect a database with the Python application.
- Open Anaconda Navigator, then select base (root) and click the Launch button to start Jupyter Notebook.
- Create a Notebook to proceed.
- Use the command below to import the Devart MongoDB module.
import devart.mongodb
The output should look like in the screenshot shown below.
- Use the connect method to establish a connection to the Netflix MongoDB database (or another database you already have). Check the credentials below to proceed.
- Server: localhost
- Database: Netflix
- User: netflix
- Password: netflix#123
- ClientLibrary and BSONLibrary: here there should be the location path to .dll files where you have installed Devart Python Connector for MongoDB. By default, these are stored here: (C:\Users\dtdinh\anaconda3\Lib\site-packages\devart\mongodb).
Feel free to copy libmongoc-1.0.dll and libbson-1.0.dll to another location for convenience.
How to create a connection and query data from MongoDB
Your Netflix MongoDB database is still empty, but now you can create a table within it to test the connectivity.
Here’s a simple way of doing it with execute method of cursor class. This will let you create a table using an approach similar to DDL statements in SQL.
Let’s add attributes to our users collection: name, email, and password.
# Create a table: users in Netflix database
# Create a cusor from my_connection
cursor = my_connection.cursor()
cursor.execute("create table users(name , email, password)")
Check the screenshot below to see how this should work.
Next, you will need to insert one record into users table in the Netflix database by using the execute method and INSERT command.
#Insert one record into users
tablecursor.execute("insert into users(name , email, password) values(:parameter1,:parameter2,:parameter3)" ,("John Doe","[email protected]","password"))
After the insertion, let’s query data by using the SELECT table statement.
cursor.execute("SELECT * FROM users")for row in cursor.fetchall(): print(row)
Conclusion
Now that you have a clear idea of how to connect MongoDB using Python Connector from Devart to perform DML operations, you will be able to use this approach when building data-rich Python applications, saving substantial amounts of time on integration tasks.
Apart from simplicity, Python Connectors from Devart will also provide you with support of all MongoDB and Python data types, providing extra options for data mapping. With this connectivity solution, you can submit multiple update statements to the MongoDB database server for processing as a batch to improve execution time, and improve overall security by using encryption support feature.
Feel free to explore MongoDB Python Connectors from Devart to learn more about the benefits you can get!