Python MongoDB Connectivity
MongoDB is a database system designed to work with flexible, document-based data. Python applications can communicate with MongoDB through the PyMongo driver, which provides the required interface for database operations.
With Python and MongoDB connected, developers can create databases and collections, insert documents, retrieve stored information, and manage records programmatically. These operations form the basic CRUD workflow: Create, Read, Update, and Delete.
This tutorial demonstrates how to install PyMongo, establish a local MongoDB connection, create a database and collection, insert an employee document, and verify the stored information through the MongoDB shell.
Table of Contents

Steps for Python MongoDB Connectivity
1. Install the Required Driver
Python requires a MongoDB driver to communicate with the database. PyMongo provides the Python interface needed for connecting to MongoDB and executing database operations.
Install it through pip using:
$ pip install pymongo
After the package has been installed, it can be imported into a Python program to create a MongoDB connection.
2. Create a Python Script
Now create a Python file named connect.py. The following program establishes a connection, selects a database, creates an employee document, inserts it into a collection, and then retrieves the inserted record.
from pymongo import MongoClient
import pprint
# Step 1: Creating an instance of MongoClient
client = MongoClient('mongodb://localhost:27017/')
# Step 2: Creating a database
db = client['example_database']
# Step 3: Defining a record
employee = {
"id": "101",
"name": "John Doe",
"profession": "Software Developer",
"department": "Engineering"
}
# Step 4: Creating a collection
employees = db['employees']
# Step 5: Inserting the record
employees.insert_one(employee)
# Step 6: Fetching and displaying the record
print("Inserted Record:")
pprint.pprint(employees.find_one({"id": "101"}))
Understanding the Code
The MongoClient class is used to create the connection with the MongoDB server. In this example, the connection uses the local MongoDB URI mongodb://localhost:27017/.
The database is referenced through example_database, while employees represents the collection where the document will be stored.
The employee dictionary contains information such as the employee ID, name, profession, and department. The insert_one() method adds this document to the collection. Finally, find_one() searches for the document using its ID.
3. Execute the Python Script
Save the program as connect.py and run it from the terminal:
$ python connect.py
If the connection and insertion are successful, the program displays the stored employee document. The output can look similar to:
Inserted Record:
{'_id': ObjectId('64fcb3d0c2d10e5e7a21f1c9'),
'department': 'Engineering',
'id': '101',
'name': 'John Doe',
'profession': 'Software Developer'}
MongoDB automatically creates an _id field for the document when one is not explicitly supplied.
4. Access the MongoDB Shell
After inserting the record, you can use the MongoDB shell to inspect the database and collection.
Open the MongoDB shell with:
$ mongo
This provides a command-line interface for interacting with MongoDB.
5. Check Available Databases
To display the databases available in the MongoDB environment, use:
> show dbs
The command lists the databases that are available to the current MongoDB environment.
6. Verify the Collection
Switch to the database created in the Python program:
> use example_database
> show collections
The show collections command displays the collections available inside example_database. The employees collection should appear because it was created when the document was inserted.
7. View Stored Records
To display the documents contained in the employees collection, execute:
> db.employees.find().pretty()
The inserted employee document can be displayed in a readable format similar to:
{
"_id": ObjectId("64fcb3d0c2d10e5e7a21f1c9"),
"id": "101",
"name": "John Doe",
"profession": "Software Developer",
"department": "Engineering"
}
This confirms that the document created through Python has been stored in the MongoDB collection.
Key Updates for Modern Implementations
When developing a Python application that communicates with MongoDB, several practices can make the implementation easier to manage and more suitable for larger applications.
MongoDB URI
Specify the MongoDB connection URI explicitly so that the application clearly defines which MongoDB server it should communicate with. For a local setup, the example uses:
mongodb://localhost:27017/
Environment Variables
Database connection information and sensitive credentials should be stored using environment variables rather than being directly written into application source code. This provides a safer way to manage configuration values.
Error Handling
Database operations can be placed inside try and except blocks so that connection or operation-related errors can be handled without unexpectedly terminating the application.
Indexing
MongoDB indexes can improve query performance when collections contain large amounts of information. Appropriate indexing can make frequently used queries faster and more efficient.
Complete Advance AI Topics: Click Here
SQL Tutorial: Click Here
YT:- DecodeIT
Frequently Asked Questions
1. How can Python connect to MongoDB?
Python can communicate with MongoDB using the PyMongo driver and the MongoClient class.
2. What is PyMongo?
PyMongo is a Python driver that provides an interface for interacting with MongoDB databases from Python programs.
3. Do I need to install PyMongo separately?
Yes. PyMongo can be installed using pip with:
pip install pymongo
4. What is the MongoDB connection string used in this example?
The example connects to a local MongoDB server using:
mongodb://localhost:27017/
5. Can Python connect to MongoDB Atlas?
Yes. Python applications can connect to MongoDB Atlas by using the appropriate MongoDB connection string supplied for the Atlas deployment.
6. What is used to insert a document in MongoDB?
PyMongo provides the insert_one() method for adding a single document to a MongoDB collection.
Conclusion
Python MongoDB connectivity provides a practical way to work with document-based data directly from Python applications. With PyMongo, developers can establish a database connection, select databases and collections, insert documents, retrieve records, and perform other database operations.
The basic workflow demonstrated here starts with installing PyMongo and creating a MongoClient connection. After that, a database and collection can be accessed, documents can be inserted, and the stored information can be verified through Python or the MongoDB shell.
For larger applications, practices such as environment-based configuration, error handling, and suitable indexing can also be incorporated into the database implementation.
Keywords: Python MongoDB Connectivity, How to connect to MongoDB through Python,Python MongoDB Connectivity, What is MongoDB connectivity, python mongoDB connectivity, Do I need to install MongoDB to use PyMongo, Is the motor better than PyMongo, mongodb connection example, mongodb connection issues, mongodb not connecting, how to connect mongodb atlas with python, python mongodb connection string, python connect to mongodb example, python mongodb test connection, Python MongoDB Connectivity: A Step-by-Step Guide, python connect mongodb atlas, python mongodb connection with authentication, how to connect mongodb with python,Python MongoDB Connectivity