MongoDB CRUD Tutorials in Python: A Step-by-Step Guide

In this tutorial, we’ll explore how to perform CRUD (Create, Read, Update, Delete) operations using MongoDB in a Python application.

Posted on

MongoDB is a popular NoSQL database that excels at handling unstructured or semi-structured data. In this tutorial, we’ll explore how to perform CRUD (Create, Read, Update, Delete) operations using MongoDB in a Python application. We’ll cover each step and provide practical examples with detailed explanations to help you get started.

Prerequisites

Before we begin, make sure you have the following prerequisites:

  1. MongoDB: MongoDB should be installed and running. You can download it from the official MongoDB website.

  2. Python: Ensure you have Python installed on your system. You can download Python from the official Python website.

  3. PyMongo: Install the pymongo package, which is the official MongoDB driver for Python. You can install it using pip:

    pip install pymongo
    

Step 1: Connecting to MongoDB

To use MongoDB in a Python application, establish a connection to the database.

import pymongo

# Create a MongoDB client and connect
try:
    client = pymongo.MongoClient("mongodb://localhost:27017/")
    db = client["your_database_name"]

    print("Connected to MongoDB")

except Exception as e:
    print(f"Error: {e}")

Replace "mongodb://localhost:27017/" with your MongoDB server URL and "your_database_name" with the desired database name.

Step 2: Creating a Collection

In MongoDB, data is stored in collections. Let’s create a collection named “users” to demonstrate CRUD operations.

try:
    users_collection = db["users"]

    print("Collection 'users' created successfully")

except Exception as e:
    print(f"Error: {e}")

Step 3: Inserting Data

Now, let’s insert a new user document into the “users” collection.

try:
    user_data = {
        "username": "john_doe",
        "email": "[email protected]"
    }

    user_id = users_collection.insert_one(user_data).inserted_id
    print(f"Data inserted with ID: {user_id}")

except Exception as e:
    print(f"Error: {e}")

Step 4: Querying Data

Retrieve data from the “users” collection.

try:
    query = users_collection.find()

    for user in query:
        print(f"ID: {user['_id']}, Username: {user['username']}, Email: {user['email']}")

except Exception as e:
    print(f"Error: {e}")

Step 5: Updating Data

Update a user’s email in the “users” collection.

try:
    query = {"username": "john_doe"}
    new_email = {"$set": {"email": "[email protected]"}}

    users_collection.update_one(query, new_email)
    print("Data updated successfully")

except Exception as e:
    print(f"Error: {e}")

Step 6: Deleting Data

Delete a user from the “users” collection.

try:
    query = {"username": "john_doe"}

    users_collection.delete_one(query)
    print("Data deleted successfully")

except Exception as e:
    print(f"Error: {e}")

Step 7: Error Handling and Cleanup

Proper error handling is essential when working with databases. Close the MongoDB client when done.

finally:
    if 'client' in locals():
        client.close()
        print("Connection closed")

Conclusion

In this tutorial, we’ve covered the basics of performing CRUD operations using MongoDB in a Python application. You’ve learned how to connect to MongoDB, create a collection, insert data, query data, update documents, and delete documents. These fundamental skills will serve as a solid foundation for building more complex database-driven applications with MongoDB and Python.