MongoDB Basics Using Python: A Step-by-Step Guide

MongoDB is a highly popular NoSQL database that provides flexibility in storing data as documents in collections. Unlike traditional relational databases, MongoDB uses a dynamic schema, which allows you to store various types of data without predefined structures. In this article, we will walk you through setting up MongoDB with Python, including connecting to a MongoDB database, performing CRUD (Create, Read, Update, Delete) operations, and handling collections using the pymongo library.

Let’s start by setting up the environment and move step-by-step through code examples.

Setting Up Python and MongoDB

Before we begin working with MongoDB, you need to install Python and set up a virtual environment.

1. Check Python Version: Make sure Python is installed on your system. You can check the version by running:

    # Check Python version
    python --version

    2. Set Up a Virtual Environment: It is a good practice to work in a virtual environment to isolate your project’s dependencies.

    # Create a virtual environment
    python -m venv venv
    
    # Activate the virtual environment
    venv\Scripts\activate

    3. Upgrade pip: Once the virtual environment is activated, upgrade pip to ensure you are working with the latest version.

    # Upgrade pip
    python.exe -m pip install --upgrade pip

    4. Install pymongo: To interact with MongoDB, we will use the pymongo library, which provides an interface between Python and MongoDB.

    # Install pymongo
    pip install pymongo

    Connecting to MongoDB

    To connect to a MongoDB instance, we will use the MongoClient from the pymongo package. Here’s how you can connect to a MongoDB cluster using a connection string.

    import pymongo
    
    # Create a MongoClient
    client = pymongo.MongoClient("mongodb string")
    
    # Access the database
    db = client['sample_mflix']
    
    # Access a collection
    collection = db['comments']

    In this example:

    • MongoClient connects to the MongoDB Atlas cluster using a connection string.
    • We are accessing a database called sample_mflix and a collection named comments.

    Performing CRUD Operations

    1. Read (Querying Data)

    To read data from MongoDB, we use the find method to retrieve documents from the collection. You can filter the results by passing a query object. For example, the code below retrieves all comments where the email is “[email protected]“:

    # Query the collection
    result = collection.find({"email": "[email protected]"})
    
    # Print the documents
    count = 0
    for document in result:
        print(document)
        count += 1
    
    print(f"Total documents found: {count}")

    2. Insert (Adding Data)

    To insert data into MongoDB, you can use either insert_one for inserting a single document or insert_many for inserting multiple documents at once.

    • Inserting a Single Document:
    document = {"name": "Adam", "age": 30}
    collection.insert_one(document)

    Inserting Multiple Documents:

    documents = [
        {"name": "Alice", "age": 28},
        {"name": "Bob", "age": 32},
    ]
    collection.insert_many(documents)

    You can also create a loop to continuously add records from user input:

    while True:
        choice = input("Do you want to add more records? (y/n): ")
        if choice.lower() == 'y':
            user_name = input("Name: ")
            age = int(input("Age: "))
            document = {"name": user_name, "age": age}
            collection.insert_one(document)
        else:
            client.close()
            exit()

    3. Update (Modifying Data)

    MongoDB allows you to update documents using update_one (for a single document) or update_many (for multiple documents). You need to specify the query to locate the documents you want to update and provide the new values.

    • Update a Single Document:
    query = {"name": "John"}
    new_values = {"$set": {"age": 56}}
    collection.update_one(query, new_values)

    Update Multiple Documents:

    query = {"age": {"$gt": 25}}  # Find all documents where age is greater than 25
    new_values = {"$set": {"age": 35}}
    collection.update_many(query, new_values)

    4. Delete (Removing Data)

    To delete data from MongoDB, you can use delete_one to remove a single document or delete_many to remove multiple documents that match a given query.

    • Delete a Single Document:
    query = {"name": "John"}
    collection.delete_one(query)

    Delete Multiple Documents:

    query = {"age": {"$gt": 30}}  # Delete all records where age > 30
    collection.delete_many(query)

    Closing the Connection

    After completing your operations, it is good practice to close the connection to the MongoDB server.

    client.close()

    Complete Code for Read Data

    # python --version
    # python -m venv venv
    # venv\Scripts\activate
    # python.exe -m pip install --upgrade pip
    
    # pip install pymongo
    
    import pymongo
    
    # Create a MongoClient
    client = pymongo.MongoClient("mongodb string")
    
    # Access the database
    db = client['sample_mflix']
    
    # Access a collection
    obj = db['comments']
    
    result = obj.find({"email": "[email protected]"})
    # print(result)
    # Loop through and print each document
    
    count = 0
    
    for document in result:
        print(document)
        count += 1
    
    print(count)
    
    client.close()

    Complete Code for Insert Data

    import pymongo
    
    # Establish a connection to the MongoDB server
    client = pymongo.MongoClient("mongodb string")
    
    # Select the database and collection
    db = client["sample_mflix"]
    collection = db["demo"]
    
    # Insert one document
    # document = {"name": "Adam", "age": 30}
    # collection.insert_one(document)
    
    # Insert multiple documents
    # documents = [
    #     {"name": "Alice", "age": 28},
    #     {"name": "Bob", "age": 32},
    # ]
    # collection.insert_many(documents)
    
    while True:
        choice = input("Do you want to add more records?")
        if choice == 'y':
            user_name = input("Name:")
            age = int(input("Age:"))
    
            document = {"name": user_name, "age": age}
            collection.insert_one(document)
        else:
            client.close()
            exit()

    Complete Code for Update Data

    import pymongo
    
    # Establish a connection to the MongoDB server
    client = pymongo.MongoClient("mongodb string")
    
    # Select the database and collection
    db = client["sample_mflix"]
    collection = db["demo"]
    
    # Update a single document
    # query = {"name": "John"}
    # new_values = {"$set": {"age": 56}}
    # collection.update_one(query, new_values)
    
    # Update multiple documents
    query = {"age": {"$gt": 25}}  # Update all records where age > 25
    new_values = {"$set": {"age": 35}}
    collection.update_many(query, new_values)
    
    client.close()

    Complete Code for Delete Data

    import pymongo
    
    # Establish a connection to the MongoDB server
    client = pymongo.MongoClient("mongodb string")
    
    # Select the database and collection
    db = client["sample_mflix"]
    collection = db["demo"]
    
    # Delete one document
    # query = {"name": "John"}
    # collection.delete_one(query)
    
    # Delete multiple documents
    # query = {"age": {"$gt": 30}}  # Delete all records where age > 30
    # collection.delete_many(query)
    
    client.close()

    Conclusion

    In this article, we have covered the basic operations (CRUD) using MongoDB and Python. The pymongo library allows you to seamlessly interact with MongoDB, providing powerful tools to manage and query your data. Whether you are reading, inserting, updating, or deleting data, MongoDB offers the flexibility needed to handle large datasets without predefined schemas.

    By following this guide, you should now be equipped to start using MongoDB with Python for your projects, manage databases, and handle collections effectively.

    Subscribe
    Notify of
    guest
    0 Comments
    Oldest
    Newest Most Voted
    Inline Feedbacks
    View all comments
    0
    Would love your thoughts, please comment.x
    ()
    x