logologo
  • AI Tools

    DB Query GeneratorMock InterviewResume BuilderLearning Path GeneratorCheatsheet GeneratorAgentic Prompt GeneratorCompany ResearchCover Letter Generator
  • XpertoAI
  • MVP Ready
  • Resources

    CertificationsTopicsExpertsCollectionsArticlesQuestionsVideosJobs
logologo

Elevate Your Coding with our comprehensive articles and niche collections.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Xperto-AI
  • Certifications
  • Python
  • GenAI
  • Machine Learning

Interviews

  • DSA
  • System Design
  • Design Patterns
  • Frontend System Design
  • ReactJS

Procodebase © 2024. All rights reserved.

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

CRUD Operations in MongoDB with Python

author
Generated by
ProCodebase AI

08/11/2024

Python

Sign in to read full article

MongoDB is a popular NoSQL database that stores data in a flexible, JSON-like format called BSON (Binary JSON). It is particularly well-suited for handling large volumes of unstructured data. When working with MongoDB and Python, you'll find the pymongo library to be very useful as it provides a straightforward way to interact with your MongoDB database.

In this blog, we’ll break down the basic CRUD operations that you can perform with Python and MongoDB.

Setting Up Your Environment

Prerequisites

To follow along, you'll need to have Python and MongoDB installed on your system. Also, ensure you have the pymongo library installed. You can install it via pip:

pip install pymongo

Connecting to MongoDB

First, let’s connect to our MongoDB instance. Here’s a simple piece of code that connects to the default MongoDB URI:

from pymongo import MongoClient # Connect to MongoDB client = MongoClient('mongodb://localhost:27017/') # Access the 'testdb' database db = client['testdb']

Creating Documents (C)

The first operation we’ll look at is creating documents. In MongoDB, documents are akin to rows in traditional SQL databases. Let's create a collection called users and insert some documents.

Inserting a Single Document

# Define a user document user = { "name": "Alice", "age": 30, "status": "active" } # Insert the document into the 'users' collection result = db.users.insert_one(user) print(f"Inserted document ID: {result.inserted_id}")

Inserting Multiple Documents

# Define multiple users users = [ {"name": "Bob", "age": 25, "status": "active"}, {"name": "Charlie", "age": 28, "status": "inactive"} ] # Insert multiple documents results = db.users.insert_many(users) print("Inserted document IDs:", results.inserted_ids)

Reading Documents (R)

After inserting documents, the next step is to read data from your database. There are several ways to query data in MongoDB.

Finding a Single Document

You can retrieve a single document based on a specific criterion:

# Find one document user = db.users.find_one({"name": "Alice"}) print(user)

Finding Multiple Documents

To retrieve multiple documents, you can use find():

# Find all active users active_users = db.users.find({"status": "active"}) print("Active Users:") for user in active_users: print(user)

Using Projection

Sometimes, you might only want to retrieve certain fields from the documents. You can achieve this with projection:

# Find names and ages of all users users_projection = db.users.find({}, {"name": 1, "age": 1}) for user in users_projection: print(user)

Updating Documents (U)

Updating documents in MongoDB is straightforward. Let's explore how to update existing records.

Updating a Single Document

# Update Alice's status update_result = db.users.update_one( {"name": "Alice"}, {"$set": {"status": "inactive"}} ) print(f"Modified count: {update_result.modified_count}")

Updating Multiple Documents

You can also update multiple documents with a single command:

# Set all active users to inactive update_results = db.users.update_many( {"status": "active"}, {"$set": {"status": "inactive"}} ) print(f"Modified count (multiple): {update_results.modified_count}")

Deleting Documents (D)

The last operation we'll cover is deleting documents. It’s essential to handle this carefully as it can lead to data loss if not done correctly.

Deleting a Single Document

# Delete a single document delete_result = db.users.delete_one({"name": "Charlie"}) print(f"Deleted count: {delete_result.deleted_count}")

Deleting Multiple Documents

To remove multiple documents based on a condition, you can use:

# Delete all inactive users delete_results = db.users.delete_many({"status": "inactive"}) print(f"Deleted count (multiple): {delete_results.deleted_count}")

Wrapping Up

You’ve now learned how to perform CRUD operations in MongoDB using Python. These operations form the backbone of database interaction and are crucial for any data-driven application. With these skills at your fingertips, you can start building robust applications using MongoDB and Python with confidence. Happy coding!

Popular Tags

PythonMongoDBCRUD operations

Share now!

Like & Bookmark!

Related Collections

  • Mastering NLP with spaCy

    22/11/2024 | Python

  • Mastering NumPy: From Basics to Advanced

    25/09/2024 | Python

  • Automate Everything with Python: A Complete Guide

    08/12/2024 | Python

  • Python with MongoDB: A Practical Guide

    08/11/2024 | Python

  • Mastering Computer Vision with OpenCV

    06/12/2024 | Python

Related Articles

  • Working with Redis Data Types in Python

    08/11/2024 | Python

  • Threading and Concurrency in Python

    13/01/2025 | Python

  • Advanced Exception Handling Techniques in Python

    13/01/2025 | Python

  • Object Tracking with Python

    06/12/2024 | Python

  • Understanding Shape Analysis with Python

    06/12/2024 | Python

  • Deploying and Managing MongoDB Databases in Cloud Environments with Python

    08/11/2024 | Python

  • Deploying Automation Scripts with Python

    08/12/2024 | Python

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design